-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathState.js
85 lines (79 loc) · 2.17 KB
/
State.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
export function getActiveStateExceptDrawer(param) {
const state = param;
if (!state.routes) {
return state;
}
if (state.routes[state.index].routeName === 'DrawerOpen') {
return getActiveState(state.routes[0]);
}
return getActiveState(state.routes[state.index]);
}
export function isActiveRoute(state, routeName) {
if (state.routeName === routeName) {
return true;
}
if (!state.routes) {
return state.routeName === routeName;
}
if (state.routes[state.index].routeName === 'DrawerOpen') {
return isActiveRoute(state.routes[0], routeName);
}
return isActiveRoute(state.routes[state.index], routeName);
}
export function getRouteNameByKey(state, key) {
if (state.key === key) {
return state.routeName;
}
if (!state.routes) {
return state.routeName;
}
if (state.routes[state.index].key === key) {
return state.routes[state.index].routeName;
}
return getRouteNameByKey(state.routes[state.index], key);
}
export function getActiveState(param, parent) {
const state = param;
if (!state.routes) {
return { ...state, parent };
}
return getActiveState(state.routes[state.index], { ...state, parent });
}
export function getParent(state, routeName, parent) {
if (state.routeName === routeName) {
return parent;
}
if (!state.routes) {
return null;
}
for (let i = 0; i < state.routes.length; i += 1) {
const res = getParent(state.routes[i], routeName, state);
if (res) {
return res;
}
}
return null;
}
export function inject(state, key, index, routes) {
if (!state.routes) {
return state;
}
if (state.key === key) {
if (routes) {
return { ...state, routes, index };
}
return { ...state, index };
}
return { ...state, routes: state.routes.map(x => inject(x, key, index, routes)) };
}
export function popPrevious(state, routeName) {
const parent = getParent(state, routeName);
// console.log('FOUND PARENT:', JSON.stringify(parent));
const { key, index } = parent;
if (index) {
const routes = [...parent.routes.slice(0, index - 1), ...parent.routes.slice(index)];
const newState = inject(state, key, index - 1, routes);
return newState;
}
return state;
}