-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Navigation.ts
384 lines (331 loc) · 13.9 KB
/
Navigation.ts
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
import {findFocusedRoute} from '@react-navigation/core';
import type {EventArg, NavigationContainerEventMap} from '@react-navigation/native';
import {CommonActions, getPathFromState, StackActions} from '@react-navigation/native';
import Log from '@libs/Log';
import * as ReportUtils from '@libs/ReportUtils';
import {getReport} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import type {HybridAppRoute, Route} from '@src/ROUTES';
import ROUTES, {HYBRID_APP_ROUTES} from '@src/ROUTES';
import {PROTECTED_SCREENS} from '@src/SCREENS';
import type {Report} from '@src/types/onyx';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import originalDismissModal from './dismissModal';
import originalDismissModalWithReport from './dismissModalWithReport';
import originalGetTopmostReportActionId from './getTopmostReportActionID';
import originalGetTopmostReportId from './getTopmostReportId';
import linkingConfig from './linkingConfig';
import linkTo from './linkTo';
import navigationRef from './navigationRef';
import switchPolicyID from './switchPolicyID';
import type {NavigationStateRoute, State, StateOrRoute, SwitchPolicyIDParams} from './types';
let resolveNavigationIsReadyPromise: () => void;
const navigationIsReadyPromise = new Promise<void>((resolve) => {
resolveNavigationIsReadyPromise = resolve;
});
let pendingRoute: Route | null = 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;
}
function canNavigate(methodName: string, params: Record<string, unknown> = {}): boolean {
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 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);
// Re-exporting the dismissModal here to fill in default value for navigationRef. The dismissModal isn't defined in this file to avoid cyclic dependencies.
const dismissModal = (reportID?: string, ref = navigationRef) => {
if (!reportID) {
originalDismissModal(ref);
return;
}
const report = getReport(reportID);
originalDismissModalWithReport({reportID, ...report}, ref);
};
// Re-exporting the dismissModalWithReport here to fill in default value for navigationRef. The dismissModalWithReport isn't defined in this file to avoid cyclic dependencies.
// This method is needed because it allows to dismiss the modal and then open the report. Within this method is checked whether the report belongs to a specific workspace. Sometimes the report we want to check, hasn't been added to the Onyx yet.
// Then we can pass the report as a param without getting it from the Onyx.
const dismissModalWithReport = (report: Report | EmptyObject, ref = navigationRef) => originalDismissModalWithReport(report, ref);
/** Method for finding on which index in stack we are. */
function getActiveRouteIndex(stateOrRoute: StateOrRoute, index?: number): number | undefined {
if ('routes' in stateOrRoute && stateOrRoute.routes) {
const childActiveRoute = stateOrRoute.routes[stateOrRoute.index ?? 0];
return getActiveRouteIndex(childActiveRoute, stateOrRoute.index ?? 0);
}
if ('state' in stateOrRoute && stateOrRoute.state?.routes) {
const childActiveRoute = stateOrRoute.state.routes[stateOrRoute.state.index ?? 0];
return getActiveRouteIndex(childActiveRoute, stateOrRoute.state.index ?? 0);
}
if (
'name' in stateOrRoute &&
(stateOrRoute.name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR || stateOrRoute.name === NAVIGATORS.LEFT_MODAL_NAVIGATOR || stateOrRoute.name === NAVIGATORS.FULL_SCREEN_NAVIGATOR)
) {
return 0;
}
return index;
}
/**
* Function that generates dynamic urls from paths passed from OldDot
*/
function parseHybridAppUrl(url: HybridAppRoute | Route): Route {
switch (url) {
case HYBRID_APP_ROUTES.MONEY_REQUEST_CREATE:
return ROUTES.MONEY_REQUEST_CREATE.getRoute(CONST.IOU.TYPE.REQUEST, CONST.IOU.OPTIMISTIC_TRANSACTION_ID, ReportUtils.generateReportID());
default:
return url;
}
}
/**
* Gets distance from the path in root navigator. In other words how much screen you have to pop to get to the route with this path.
* The search is limited to 5 screens from the top for performance reasons.
* @param path - Path that you are looking for.
* @return - Returns distance to path or -1 if the path is not found in root navigator.
*/
function getDistanceFromPathInRootNavigator(path?: string): number {
let currentState = navigationRef.getRootState();
for (let index = 0; index < 5; index++) {
if (!currentState.routes.length) {
break;
}
const pathFromState = getPathFromState(currentState, linkingConfig.config);
if (path === pathFromState.substring(1)) {
return index;
}
currentState = {...currentState, routes: currentState.routes.slice(0, -1), index: currentState.index - 1};
}
return -1;
}
/** Returns the current active route */
function getActiveRoute(): string {
const currentRoute = navigationRef.current && navigationRef.current.getCurrentRoute();
if (!currentRoute?.name) {
return '';
}
if (currentRoute?.path) {
return currentRoute.path;
}
const routeFromState = getPathFromState(navigationRef.getRootState(), linkingConfig.config);
if (routeFromState) {
return routeFromState;
}
return '';
}
/**
* 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 routePath Path to check
* @return is active
*/
function isActiveRoute(routePath: Route): boolean {
let activeRoute = getActiveRoute();
activeRoute = activeRoute.startsWith('/') ? activeRoute.substring(1) : activeRoute;
// We remove redundant (consecutive and trailing) slashes from path before matching
return activeRoute === routePath.replace(CONST.REGEX.ROUTES.REDUNDANT_SLASHES, (match, p1) => (p1 ? '/' : ''));
}
/**
* Main navigation method for redirecting to a route.
* @param [type] - Type of action to perform. Currently UP is supported.
*/
function navigate(route: Route = ROUTES.HOME, type?: string) {
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, isActiveRoute(route));
}
/**
* @param fallbackRoute - Fallback route if pop/goBack action should, but is not possible within RHP
* @param shouldEnforceFallback - Enforces navigation to fallback route
* @param shouldPopToTop - Should we navigate to LHN on back press
*/
function goBack(fallbackRoute?: Route, 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 = rootState.routes.at(-1);
// If the user comes from a different flow (there is more than one route in ModalNavigator) 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?.name === NAVIGATORS.LEFT_MODAL_NAVIGATOR) && (lastRoute.state?.index ?? 0) > 0) {
navigationRef.current.goBack();
return;
}
}
if (shouldEnforceFallback || (isFirstRouteInNavigator && fallbackRoute)) {
navigate(fallbackRoute, CONST.NAVIGATION.TYPE.UP);
return;
}
const isCentralPaneFocused = findFocusedRoute(navigationRef.current.getState())?.name === NAVIGATORS.CENTRAL_PANE_NAVIGATOR;
const distanceFromPathInRootNavigator = getDistanceFromPathInRootNavigator(fallbackRoute ?? '');
// Allow CentralPane to use UP with fallback route if the path is not found in root navigator.
if (isCentralPaneFocused && fallbackRoute && distanceFromPathInRootNavigator === -1) {
navigate(fallbackRoute, CONST.NAVIGATION.TYPE.FORCED_UP);
return;
}
// Add possibility to go back more than one screen in root navigator if that screen is on the stack.
if (isCentralPaneFocused && fallbackRoute && distanceFromPathInRootNavigator > 0) {
navigationRef.current.dispatch(StackActions.pop(distanceFromPathInRootNavigator));
return;
}
navigationRef.current.goBack();
}
/**
* Reset the navigation state to Home page
*/
function resetToHome() {
const rootState = navigationRef.getRootState();
const bottomTabKey = rootState.routes.find((item: NavigationStateRoute) => item.name === NAVIGATORS.BOTTOM_TAB_NAVIGATOR)?.state?.key;
if (bottomTabKey) {
navigationRef.dispatch({...StackActions.popToTop(), target: bottomTabKey});
}
navigationRef.dispatch({...StackActions.popToTop(), target: rootState.key});
}
/**
* Close the full screen modal.
*/
function closeFullScreen() {
const rootState = navigationRef.getRootState();
navigationRef.dispatch({...StackActions.popToTop(), target: rootState.key});
}
/**
* Update route params for the specified route.
*/
function setParams(params: Record<string, unknown>, routeKey = '') {
navigationRef.current?.dispatch({
...CommonActions.setParams(params),
source: routeKey,
});
}
/**
* Returns the current active route without the URL params
*/
function getActiveRouteWithoutParams(): string {
return getActiveRoute().replace(/\?.*/, '');
}
/** Returns the active route name from a state event from the navigationRef */
function getRouteNameFromStateEvent(event: EventArg<'state', false, NavigationContainerEventMap['state']['data']>): string | undefined {
if (!event.data.state) {
return;
}
const currentRouteName = event.data.state.routes.at(-1)?.name;
// Check to make sure we have a route name
if (currentRouteName) {
return currentRouteName;
}
}
/**
* 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;
}
function isNavigationReady(): Promise<void> {
return navigationIsReadyPromise;
}
function setIsNavigationReady() {
goToPendingRoute();
resolveNavigationIsReadyPromise();
}
/**
* Checks if the navigation state contains routes that are protected (over the auth wall).
*
* @param state - react-navigation state object
*/
function navContainsProtectedRoutes(state: State | undefined): boolean {
if (!state?.routeNames || !Array.isArray(state.routeNames)) {
return false;
}
// If one protected screen is in the routeNames then other screens are there as well.
return state?.routeNames.includes(PROTECTED_SCREENS.CONCIERGE);
}
/**
* 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 resolve immediately.
*
* @function
* @returns A promise that resolves when the one of the PROTECTED_SCREENS screen is available in the nav tree.
*
* @example
* waitForProtectedRoutes()
* .then(()=> console.log('Protected routes are present!'))
*/
function waitForProtectedRoutes() {
return new Promise<void>((resolve) => {
isNavigationReady().then(() => {
const currentState = navigationRef.current?.getState();
if (navContainsProtectedRoutes(currentState)) {
resolve();
return;
}
const unsubscribe = navigationRef.current?.addListener('state', ({data}) => {
const state = data?.state;
if (navContainsProtectedRoutes(state)) {
unsubscribe?.();
resolve();
}
});
});
});
}
function navigateWithSwitchPolicyID(params: SwitchPolicyIDParams) {
if (!canNavigate('navigateWithSwitchPolicyID')) {
return;
}
return switchPolicyID(navigationRef.current, params);
}
export default {
setShouldPopAllStateOnUP,
navigate,
setParams,
dismissModal,
dismissModalWithReport,
isActiveRoute,
getActiveRoute,
getActiveRouteWithoutParams,
goBack,
isNavigationReady,
setIsNavigationReady,
getTopmostReportId,
getRouteNameFromStateEvent,
getTopmostReportActionId,
waitForProtectedRoutes,
parseHybridAppUrl,
closeFullScreen,
navigateWithSwitchPolicyID,
resetToHome,
};
export {navigationRef};