-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathNavigation.js
338 lines (299 loc) · 11.2 KB
/
Navigation.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
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
import _ from 'lodash';
import lodashGet from 'lodash/get';
import {CommonActions, getPathFromState, StackActions} from '@react-navigation/native';
import {getActionFromState} from '@react-navigation/core';
import Log from '../Log';
import linkTo from './linkTo';
import ROUTES from '../../ROUTES';
import linkingConfig from './linkingConfig';
import navigationRef from './navigationRef';
import NAVIGATORS from '../../NAVIGATORS';
import originalGetTopmostReportId from './getTopmostReportId';
import originalGetTopMostCentralPaneRouteName from './getTopMostCentralPaneRouteName';
import originalGetTopmostReportActionId from './getTopmostReportActionID';
import getStateFromPath from './getStateFromPath';
import SCREENS, {PROTECTED_SCREENS} from '../../SCREENS';
import CONST from '../../CONST';
let resolveNavigationIsReadyPromise;
const navigationIsReadyPromise = new Promise((resolve) => {
resolveNavigationIsReadyPromise = resolve;
});
let pendingRoute = null;
let shouldPopAllStateOnUP = false;
/**
* Inform the navigation that next time user presses UP we should pop all the state back to LHN.
*/
function setShouldPopAllStateOnUP() {
shouldPopAllStateOnUP = true;
}
/**
* @param {String} methodName
* @param {Object} params
* @returns {Boolean}
*/
function canNavigate(methodName, params = {}) {
if (navigationRef.isReady()) {
return true;
}
Log.hmmm(`[Navigation] ${methodName} failed because navigation ref was not yet ready`, params);
return false;
}
// Re-exporting the getTopmostReportId here to fill in default value for state. The getTopmostReportId isn't defined in this file to avoid cyclic dependencies.
const getTopmostReportId = (state = navigationRef.getState()) => originalGetTopmostReportId(state);
// Re-exporting the getTopMostCentralPaneRouteName here to fill in default value for state. The getTopMostCentralPaneRouteName isn't defined in this file to avoid cyclic dependencies.
const getTopMostCentralPaneRouteName = (state = navigationRef.getState()) => originalGetTopMostCentralPaneRouteName(state);
// Re-exporting the getTopmostReportActionID here to fill in default value for state. The getTopmostReportActionID isn't defined in this file to avoid cyclic dependencies.
const getTopmostReportActionId = (state = navigationRef.getState()) => originalGetTopmostReportActionId(state);
/**
* Method for finding on which index in stack we are.
* @param {Object} route
* @param {Number} index
* @returns {Number}
*/
const getActiveRouteIndex = function (route, index) {
if (route.routes) {
const childActiveRoute = route.routes[route.index || 0];
return getActiveRouteIndex(childActiveRoute, route.index || 0);
}
if (route.state && route.state.routes) {
const childActiveRoute = route.state.routes[route.state.index || 0];
return getActiveRouteIndex(childActiveRoute, route.state.index || 0);
}
if (route.name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
return 0;
}
return index;
};
/**
* Main navigation method for redirecting to a route.
* @param {String} route
* @param {String} [type] - Type of action to perform. Currently UP is supported.
*/
function navigate(route = ROUTES.HOME, type) {
if (!canNavigate('navigate', {route})) {
// Store intended route if the navigator is not yet available,
// we will try again after the NavigationContainer is ready
Log.hmmm(`[Navigation] Container not yet ready, storing route as pending: ${route}`);
pendingRoute = route;
return;
}
linkTo(navigationRef.current, route, type);
}
/**
* @param {String} fallbackRoute - Fallback route if pop/goBack action should, but is not possible within RHP
* @param {Bool} shouldEnforceFallback - Enforces navigation to fallback route
* @param {Bool} shouldPopToTop - Should we navigate to LHN on back press
*/
function goBack(fallbackRoute, shouldEnforceFallback = false, shouldPopToTop = false) {
if (!canNavigate('goBack')) {
return;
}
if (shouldPopToTop) {
if (shouldPopAllStateOnUP) {
shouldPopAllStateOnUP = false;
navigationRef.current.dispatch(StackActions.popToTop());
return;
}
}
if (!navigationRef.current.canGoBack()) {
Log.hmmm('[Navigation] Unable to go back');
return;
}
const isFirstRouteInNavigator = !getActiveRouteIndex(navigationRef.current.getState());
if (isFirstRouteInNavigator) {
const rootState = navigationRef.getRootState();
const lastRoute = _.last(rootState.routes);
// If the user comes from a different flow (there is more than one route in RHP) we should go back to the previous flow on UP button press instead of using the fallbackRoute.
if (lastRoute.name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR && lastRoute.state.index > 0) {
navigationRef.current.goBack();
return;
}
}
if (shouldEnforceFallback || (isFirstRouteInNavigator && fallbackRoute)) {
navigate(fallbackRoute, CONST.NAVIGATION.TYPE.UP);
return;
}
navigationRef.current.goBack();
}
/**
* Update route params for the specified route.
*
* @param {Object} params
* @param {String} routeKey
*/
function setParams(params, routeKey) {
navigationRef.current.dispatch({
...CommonActions.setParams(params),
source: routeKey,
});
}
/**
* Dismisses the last modal stack if there is any
*
* @param {String | undefined} targetReportID - The reportID to navigate to after dismissing the modal
*/
function dismissModal(targetReportID) {
if (!canNavigate('dismissModal')) {
return;
}
const rootState = navigationRef.getRootState();
const lastRoute = _.last(rootState.routes);
switch (lastRoute.name) {
case NAVIGATORS.RIGHT_MODAL_NAVIGATOR:
case SCREENS.NOT_FOUND:
case SCREENS.REPORT_ATTACHMENTS:
// if we are not in the target report, we need to navigate to it after dismissing the modal
if (targetReportID && targetReportID !== getTopmostReportId(rootState)) {
const state = getStateFromPath(ROUTES.REPORT_WITH_ID.getRoute(targetReportID));
const action = getActionFromState(state, linkingConfig.config);
action.type = 'REPLACE';
navigationRef.current.dispatch(action);
// If not-found page is in the route stack, we need to close it
} else if (targetReportID && _.some(rootState.routes, (route) => route.name === SCREENS.NOT_FOUND)) {
const lastRouteIndex = rootState.routes.length - 1;
const centralRouteIndex = _.findLastIndex(rootState.routes, (route) => route.name === NAVIGATORS.CENTRAL_PANE_NAVIGATOR);
navigationRef.current.dispatch({...StackActions.pop(lastRouteIndex - centralRouteIndex), target: rootState.key});
} else {
navigationRef.current.dispatch({...StackActions.pop(), target: rootState.key});
}
break;
default: {
Log.hmmm('[Navigation] dismissModal failed because there is no modal stack to dismiss');
}
}
}
/**
* Returns the current active route
* @returns {String}
*/
function getActiveRoute() {
const currentRoute = navigationRef.current && navigationRef.current.getCurrentRoute();
const currentRouteHasName = lodashGet(currentRoute, 'name', false);
if (!currentRouteHasName) {
return '';
}
const routeFromState = getPathFromState(navigationRef.getRootState(), linkingConfig.config);
if (routeFromState) {
return routeFromState;
}
return '';
}
/** Returns the active route name from a state event from the navigationRef
* @param {Object} event
* @returns {String | undefined}
* */
function getRouteNameFromStateEvent(event) {
if (!event.data.state) {
return;
}
const currentRouteName = event.data.state.routes.slice(-1).name;
// Check to make sure we have a route name
if (currentRouteName) {
return currentRouteName;
}
}
/**
* Check whether the passed route is currently Active or not.
*
* Building path with getPathFromState since navigationRef.current.getCurrentRoute().path
* is undefined in the first navigation.
*
* @param {String} routePath Path to check
* @return {Boolean} is active
*/
function isActiveRoute(routePath) {
// We remove First forward slash from the URL before matching
return getActiveRoute().substring(1) === routePath;
}
/**
* Navigate to the route that we originally intended to go to
* but the NavigationContainer was not ready when navigate() was called
*/
function goToPendingRoute() {
if (pendingRoute === null) {
return;
}
Log.hmmm(`[Navigation] Container now ready, going to pending route: ${pendingRoute}`);
navigate(pendingRoute);
pendingRoute = null;
}
/**
* @returns {Promise}
*/
function isNavigationReady() {
return navigationIsReadyPromise;
}
function setIsNavigationReady() {
goToPendingRoute();
resolveNavigationIsReadyPromise();
}
/**
* Checks if the navigation state contains routes that are protected (over the auth wall).
*
* @function
* @param {Object} state - react-navigation state object
*
* @returns {Boolean}
*/
function navContainsProtectedRoutes(state) {
if (!state || !state.routeNames || !_.isArray(state.routeNames)) {
return false;
}
const protectedScreensNames = _.values(PROTECTED_SCREENS);
const difference = _.difference(protectedScreensNames, state.routeNames);
return !difference.length;
}
/**
* Waits for the navigation state to contain protected routes specified in PROTECTED_SCREENS constant
* If the navigation is in a state, where protected routes are available, the promise will resolve immediately.
*
* @function
* @returns {Promise<void>} A promise that resolves to `true` when the Concierge route is present.
* Rejects with an error if the navigation is not ready.
*
* @example
* waitForProtectedRoutes()
* .then(() => console.log('Protected routes are present!'))
* .catch(error => console.error(error.message));
*/
function waitForProtectedRoutes() {
return new Promise((resolve, reject) => {
const isReady = navigationRef.current && navigationRef.current.isReady();
if (!isReady) {
reject(new Error('[Navigation] is not ready yet!'));
return;
}
const currentState = navigationRef.current.getState();
if (navContainsProtectedRoutes(currentState)) {
resolve();
return;
}
let unsubscribe;
const handleStateChange = ({data}) => {
const state = lodashGet(data, 'state');
if (navContainsProtectedRoutes(state)) {
unsubscribe();
resolve();
}
};
unsubscribe = navigationRef.current.addListener('state', handleStateChange);
});
}
export default {
setShouldPopAllStateOnUP,
canNavigate,
navigate,
setParams,
dismissModal,
isActiveRoute,
getActiveRoute,
goBack,
isNavigationReady,
setIsNavigationReady,
getTopmostReportId,
getRouteNameFromStateEvent,
waitForProtectedRoutes,
getTopMostCentralPaneRouteName,
getTopmostReportActionId,
};
export {navigationRef};