-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathNavigation.ts
More file actions
1240 lines (1083 loc) · 47.5 KB
/
Copy pathNavigation.ts
File metadata and controls
1240 lines (1083 loc) · 47.5 KB
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {findFocusedRoute, getActionFromState} from '@react-navigation/core';
import type {EventArg, NavigationAction, NavigationContainerEventMap, NavigationState, PartialState} from '@react-navigation/native';
import {CommonActions, StackActions, TabActions} from '@react-navigation/native';
import {Str} from 'expensify-common';
// eslint-disable-next-line you-dont-need-lodash-underscore/omit
import omit from 'lodash/omit';
import {DeviceEventEmitter, Dimensions} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {Writable} from 'type-fest';
import {ALL_WIDE_RIGHT_MODALS, SUPER_WIDE_RIGHT_MODALS} from '@components/WideRHPContextProvider/WIDE_RIGHT_MODALS';
import SidePanelActions from '@libs/actions/SidePanel';
import clearSelectedText from '@libs/clearSelectedText/clearSelectedText';
import clearSelectedTextIfComposerBlurred from '@libs/clearSelectedTextIfComposerBlurred/clearSelectedTextIfComposerBlurred';
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import {setupHadTabNavigation} from '@libs/hadTabNavigation';
import Log from '@libs/Log';
import {setupNavigationFocusReturn} from '@libs/NavigationFocusReturn';
import {shallowCompare} from '@libs/ObjectUtils';
import {getSpan, startSpan} from '@libs/telemetry/activeSpans';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import SCREENS, {PROTECTED_SCREENS} from '@src/SCREENS';
import type {SidePanel} from '@src/types/onyx';
import {clearPreInsertedOriginalTabRoute, getPreInsertedOriginalTabRoute} from './AppNavigator/createRootStackNavigator/GetStateForActionHandlers';
import getInitialSplitNavigatorState from './AppNavigator/createSplitNavigator/getInitialSplitNavigatorState';
import originalCloseRHPFlow from './helpers/closeRHPFlow';
import getActiveTabName from './helpers/getActiveTabName';
import getPathFromState from './helpers/getPathFromState';
import getStateFromPath from './helpers/getStateFromPath';
import getTopmostReportParams from './helpers/getTopmostReportParams';
import {isFullScreenName, isOnboardingFlowName, isSplitNavigatorName} from './helpers/isNavigatorName';
import isReportOpenInRHP from './helpers/isReportOpenInRHP';
import isReportTopmostSplitNavigator from './helpers/isReportTopmostSplitNavigator';
import isSideModalNavigator from './helpers/isSideModalNavigator';
import linkTo from './helpers/linkTo';
import getMinimalAction from './helpers/linkTo/getMinimalAction';
import type {LinkToOptions} from './helpers/linkTo/types';
import replaceWithSplitNavigator from './helpers/replaceWithSplitNavigator';
import setNavigationActionToMicrotaskQueue from './helpers/setNavigationActionToMicrotaskQueue';
import {linkingConfig} from './linkingConfig';
import {SPLIT_TO_SIDEBAR} from './linkingConfig/RELATIONS';
import navigationRef from './navigationRef';
import TransitionTracker from './TransitionTracker';
import type {
NavigationPartialRoute,
NavigationRef,
NavigationRoute,
NavigationStateRoute,
ReportsSplitNavigatorParamList,
RightModalNavigatorParamList,
RootNavigatorParamList,
State,
} from './types';
type FocusedScreen = {
name: string;
params?: Record<string, unknown>;
};
// Installs the modality flag (keydown/mousedown) and focus-return listeners (focusin/click); NavigationRoot.onReady attaches the state listener once live.
setupHadTabNavigation();
setupNavigationFocusReturn();
// Screens which are part of the 2FA setup flow - used to determine when to hide the RequireTwoFactorAuthOverlay
const SET_UP_2FA_SCREENS = new Set<string>([
SCREENS.TWO_FACTOR_AUTH.DYNAMIC_ROOT,
SCREENS.TWO_FACTOR_AUTH.DYNAMIC_VERIFY,
SCREENS.TWO_FACTOR_AUTH.DYNAMIC_VERIFY_ACCOUNT,
SCREENS.TWO_FACTOR_AUTH.DYNAMIC_SUCCESS,
SCREENS.TWO_FACTOR_AUTH.SUCCESS,
SCREENS.TWO_FACTOR_AUTH.DISABLED,
SCREENS.TWO_FACTOR_AUTH.DISABLE,
]);
const MFA_FLOW_SCREENS = new Set<string>(Object.values(SCREENS.MULTIFACTOR_AUTHENTICATION));
let sidePanelNVP: OnyxEntry<SidePanel>;
// `connectWithoutView` is used here because we want to avoid unnecessary re-renders when the side panel NVP changes
// Also it is not directly connected to any UI
Onyx.connectWithoutView({
key: ONYXKEYS.NVP_SIDE_PANEL,
callback: (value) => {
sidePanelNVP = value;
},
});
function isTwoFactorSetupScreen(screen: string | undefined): boolean {
return screen ? SET_UP_2FA_SCREENS.has(screen) : false;
}
function isMFAFlowScreen(screen: string | undefined): boolean {
return screen ? MFA_FLOW_SCREENS.has(screen) : false;
}
let resolveNavigationIsReadyPromise: () => void;
const navigationIsReadyPromise = new Promise<void>((resolve) => {
resolveNavigationIsReadyPromise = resolve;
});
let pendingNavigationCall: {route: Route; options?: LinkToOptions} | null = null;
let shouldPopToSidebar = false;
/**
* Inform the navigation that next time user presses UP we should pop all the state back to LHN.
*/
function setShouldPopToSidebar(shouldPopAllStateFlag: boolean) {
shouldPopToSidebar = shouldPopAllStateFlag;
}
/**
* Returns shouldPopToSidebar variable used to determine whether should we pop all state back to LHN
* @returns shouldPopToSidebar
*/
function getShouldPopToSidebar() {
return shouldPopToSidebar;
}
/**
* Recursively get the deepest focused screen name from the navigation state.
* Unlike findFocusedRoute, this also handles the case where the nested navigator
* hasn't been mounted yet and the target screen is in params instead of state.
*/
function getDeepestFocusedScreen(route: NavigationRoute | NavigationState | PartialState<NavigationState> | undefined): FocusedScreen | undefined {
if (!route) {
return undefined;
}
// NavigationState case - has routes array
if ('routes' in route && Array.isArray(route.routes)) {
// When routes array is just one item, the index key is omitted
let focusedRoute = route.routes[0];
if ('index' in route && typeof route.index === 'number') {
focusedRoute = route.routes[route.index];
}
return getDeepestFocusedScreen(focusedRoute);
}
// Route with nested state case
if ('state' in route && route.state) {
return getDeepestFocusedScreen(route.state);
}
// Route with params.screen case (initial navigation before sidebar navigator mounts)
if ('params' in route && route.params && typeof route.params === 'object' && 'screen' in route.params) {
const params = route.params as {screen?: string; params?: Record<string, unknown>};
if (params.screen) {
return getDeepestFocusedScreen({name: params.screen, params: params.params});
}
}
// Leaf route - return the route data
if ('name' in route) {
const params = 'params' in route && route.params && typeof route.params === 'object' ? (route.params as Record<string, unknown>) : undefined;
return {name: route.name, params};
}
return undefined;
}
type CanNavigateParams = {
route?: Route;
backToRoute?: Route;
};
/**
* Checks if navigation is ready.
*/
function canNavigate(methodName: string, params: CanNavigateParams = {}): boolean {
if (navigationRef.isReady()) {
return true;
}
Log.hmmm(`[Navigation] ${methodName} failed because navigation ref was not yet ready`, params);
return false;
}
/**
* Extracts from the topmost report its id.
*/
const getTopmostReportId = (state = navigationRef.getState()) => getTopmostReportParams(state)?.reportID;
/**
* Extracts from the topmost report its action id.
*/
const getTopmostReportActionId = (state = navigationRef.getState()) => getTopmostReportParams(state)?.reportActionID;
/**
* Re-exporting the closeRHPFlow here to fill in default value for navigationRef. The closeRHPFlow isn't defined in this file to avoid cyclic dependencies.
*/
const closeRHPFlow = (ref = navigationRef) => originalCloseRHPFlow(ref);
/**
* Close the side panel on narrow layout when navigating to a different screen.
*/
function closeSidePanelOnNarrowScreen(route: Route) {
const isExtraLargeScreenWidth = Dimensions.get('window').width > variables.sidePanelResponsiveWidthBreakpoint;
if (!sidePanelNVP?.openNarrowScreen || isExtraLargeScreenWidth) {
return;
}
// Split "r/:reportID/attachment/add" by ":reportID" to get the prefix "r/" and suffix "/attachment/add"
const addAttachmentPrefix = ROUTES.REPORT_ADD_ATTACHMENT.route.split(':reportID').at(0) ?? '';
const addAttachmentSuffix = ROUTES.REPORT_ADD_ATTACHMENT.route.split(':reportID').at(1) ?? '';
const attachmentPreviewRoute = ROUTES.REPORT_ATTACHMENTS.route;
const isAddingAttachment = typeof route === 'string' && route.startsWith(addAttachmentPrefix) && route.includes(addAttachmentSuffix);
const isPreviewingAttachment = typeof route === 'string' && route.startsWith(attachmentPreviewRoute);
// If the user is navigating to an attachment route (previewing or adding), keep the side panel open
// so they still have access to the chat.
if (isAddingAttachment || isPreviewingAttachment) {
return;
}
SidePanelActions.closeSidePanel(true);
}
/**
* Returns the current active route.
*/
function getActiveRoute(): string {
if (!navigationRef.isReady()) {
return '';
}
const currentRoute = navigationRef.current?.getCurrentRoute();
if (!currentRoute?.name) {
return '';
}
const routeFromState = getPathFromState(navigationRef.getRootState());
if (routeFromState) {
return routeFromState;
}
return '';
}
/**
* Returns the route of a report opened in RHP.
*/
function getReportRHPActiveRoute(): string {
// Safe handling when navigation is not yet initialized
if (!navigationRef.isReady()) {
Log.hmmm('[src/libs/Navigation/Navigation.ts] NavigationRef is not ready. Returning empty string.');
return '';
}
if (isReportOpenInRHP(navigationRef.getRootState())) {
return getActiveRoute();
}
return '';
}
/**
* Cleans the route path by removing redundant slashes and query parameters.
* @param routePath The route path to clean.
* @returns The cleaned route path.
*/
function cleanRoutePath(routePath: string): string {
return routePath.replaceAll(CONST.REGEX.ROUTES.REDUNDANT_SLASHES, (match, p1) => (p1 ? '/' : '')).replaceAll(/\?.*/g, '');
}
/**
* 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 = getActiveRouteWithoutParams();
activeRoute = activeRoute.startsWith('/') ? activeRoute.substring(1) : activeRoute;
// We remove redundant (consecutive and trailing) slashes from path before matching
return cleanRoutePath(activeRoute) === cleanRoutePath(routePath);
}
/**
* Navigates to a specified route.
* Main navigation method for redirecting to a route.
* For detailed information about moving between screens,
* see the NAVIGATION.md documentation.
*
* @param route - The route to navigate to.
* @param options - Optional navigation options.
* @param options.forceReplace - If true, the navigation action will replace the current route instead of pushing a new one.
*/
function navigate(route: Route, options?: LinkToOptions) {
clearSelectedText();
if (!canNavigate('navigate', {route})) {
if (!navigationRef.isReady()) {
// 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}`);
pendingNavigationCall = {route, options};
}
return;
}
// Start a Sentry span for report navigation — only for exact report-open routes, not sub-pages.
// Matches: r/<id>, search/r/<id>, search/view/<id>, e/<id>
const reportOpenMatch = Str.cutAfter(route, '?').match(/^(search\/(?:r|view)|r|e)\/(\w+)$/);
if (reportOpenMatch) {
const routePrefix = reportOpenMatch.at(1);
const reportID = reportOpenMatch.at(2);
if (reportID) {
const spanId = `${CONST.TELEMETRY.SPAN_OPEN_REPORT}_${reportID}`;
let span = getSpan(spanId);
if (!span) {
const spanName = `/${routePrefix}/*`;
span = startSpan(spanId, {
name: spanName,
op: CONST.TELEMETRY.SPAN_OPEN_REPORT,
});
}
span?.setAttributes({
[CONST.TELEMETRY.ATTRIBUTE_REPORT_ID]: reportID,
[CONST.TELEMETRY.ATTRIBUTE_ROUTE_FROM]: getActiveRouteWithoutParams(),
[CONST.TELEMETRY.ATTRIBUTE_ROUTE_TO]: Str.cutAfter(route, '?'),
});
}
}
const runImmediately = !options?.waitForTransition;
TransitionTracker.runAfterTransitions({
callback: () => {
const targetRoute = route.startsWith(CONST.SAML_REDIRECT_URL) ? ROUTES.HOME : route;
linkTo(navigationRef.current, targetRoute, options);
closeSidePanelOnNarrowScreen(route);
if (options?.afterTransition) {
TransitionTracker.runAfterTransitions({callback: options.afterTransition, waitForUpcomingTransition: true});
}
},
runImmediately,
});
}
/**
* When routes are compared to determine whether the fallback route passed to the goUp function is in the state,
* these parameters shouldn't be included in the comparison.
*/
const routeParamsIgnore = ['path', 'initial', 'params', 'state', 'screen', 'policyID', 'pop'];
/**
* @private
* If we use destructuring, we will get an error if any of the ignored properties are not present in the object.
*/
function getRouteParamsToCompare(routeParams: Record<string, string | undefined>) {
return omit(routeParams, routeParamsIgnore);
}
/**
* @private
* Private method used in goUp to determine whether a target route is present in the navigation state.
*/
function doesRouteMatchToMinimalActionPayload(route: NavigationStateRoute | NavigationPartialRoute, minimalAction: Writable<NavigationAction>, compareParams: boolean) {
if (!minimalAction.payload) {
return false;
}
if (!('name' in minimalAction.payload)) {
return false;
}
const areRouteNamesEqual = route.name === minimalAction.payload.name;
if (!areRouteNamesEqual) {
return false;
}
if (!compareParams) {
return true;
}
const routeParams = getRouteParamsToCompare(route.params as Record<string, string | undefined>);
const minimalActionParams =
'params' in minimalAction.payload ? getRouteParamsToCompare(minimalAction.payload.params as Record<string, string | undefined>) : ({} as Record<string, string | undefined>);
return shallowCompare(routeParams, minimalActionParams);
}
/**
* @private
* Checks whether the given state is the root navigator state
*/
function isRootNavigatorState(state: State): state is State<RootNavigatorParamList> {
return state.key === navigationRef.current?.getRootState().key;
}
type GoBackOptions = {
/**
* If we should compare params when searching for a route in state to go up to.
* There are situations where we want to compare params when going up e.g. goUp to a specific report.
* Sometimes we want to go up and update params of screen e.g. country picker.
* In that case we want to goUp to a country picker with any params so we don't compare them.
*/
compareParams?: boolean;
// Callback to execute after the navigation transition animation completes.
afterTransition?: () => void | undefined;
// If true, waits for ongoing transitions to finish before going back. Defaults to false (goes back immediately).
waitForTransition?: boolean;
};
const defaultGoBackOptions: Required<Pick<GoBackOptions, 'compareParams' | 'waitForTransition'>> = {
compareParams: true,
waitForTransition: false,
};
/**
* @private
* Navigate to the given backToRoute taking into account whether it is possible to go back to this screen. Within one nested navigator, we can go back by any number
* of screens, but if as a result of going back we would have to remove more than one screen from the rootState,
* replace is performed so as not to lose the visited pages.
* If backToRoute is not found in the state, replace is also called then.
*
* @param backToRoute - The route to go up.
* @param options - Optional configuration that affects navigation logic, such as parameter comparison.
*/
function goUp(backToRoute: Route, options?: GoBackOptions) {
if (!canNavigate('goUp', {backToRoute}) || !navigationRef.current) {
Log.hmmm(`[Navigation] Unable to go up. Can't navigate.`);
return;
}
const compareParams = options?.compareParams ?? defaultGoBackOptions.compareParams;
const rootState = navigationRef.current.getRootState();
const stateFromPath = getStateFromPath(backToRoute);
const action = getActionFromState(stateFromPath, linkingConfig.config);
if (!action) {
Log.hmmm(`[Navigation] Unable to go up. Action is undefined.`);
return;
}
const {action: minimalAction, targetState} = getMinimalAction(action, rootState);
if (minimalAction.type !== CONST.NAVIGATION.ACTION_TYPE.NAVIGATE || !targetState) {
Log.hmmm('[Navigation] Unable to go up. Minimal action type is wrong.');
return;
}
// TabRouter does not handle POP or REPLACE (BaseRouter returns null). Switch tabs with jumpTo.
if (targetState.type === 'tab' && targetState?.key) {
const payload = minimalAction.payload as NavigationRoute;
if (!payload?.name) {
Log.hmmm('[Navigation] Unable to go up. Tab target missing screen name.');
return;
}
// Cross-tab PUSH stacks a new TAB_NAVIGATOR on the root. When an underlying TAB_NAVIGATOR
// already has the target tab active, pop to it instead of jumping — otherwise the pushed
// tab's deep leaf lingers and resurfaces with a close animation on later tab switches.
const topRootIndex = rootState.index ?? rootState.routes.length - 1;
const underlyingTabNavIndex = rootState.routes.findLastIndex(
(route, idx) => idx < topRootIndex && route.name === NAVIGATORS.TAB_NAVIGATOR && route.state?.routes?.at(route.state?.index ?? 0)?.name === payload.name,
);
if (underlyingTabNavIndex !== -1) {
navigationRef.current.dispatch(StackActions.pop(topRootIndex - underlyingTabNavIndex));
return;
}
const jumpParams = 'params' in payload ? payload.params : undefined;
navigationRef.current.dispatch({
...TabActions.jumpTo(payload.name, jumpParams),
target: targetState.key,
});
return;
}
const indexOfBackToRoute = targetState.routes.findLastIndex((route) => doesRouteMatchToMinimalActionPayload(route, minimalAction, compareParams));
const distanceToPop = targetState.routes.length - indexOfBackToRoute - 1;
// If we need to pop more than one route from rootState, we replace the current route to not lose visited routes from the navigation state
if (indexOfBackToRoute === -1 || (isRootNavigatorState(targetState) && distanceToPop > 1)) {
const replaceAction = {...minimalAction, type: CONST.NAVIGATION.ACTION_TYPE.REPLACE} as NavigationAction;
navigationRef.current.dispatch(replaceAction);
return;
}
/**
* If we are not comparing params, we want to use popTo action because it will replace params in the route already existing in the state if necessary.
*/
if (!compareParams) {
navigationRef.current.dispatch({...minimalAction, type: CONST.NAVIGATION.ACTION_TYPE.POP_TO});
return;
}
// For TAB_NAVIGATOR targets, POP_TO restores nested state from the payload (#89006). Skip when
// there's nothing to pop — POP_TO would otherwise pop to an older matching route (#89209).
if (distanceToPop > 0 && (minimalAction.payload as {name?: string} | undefined)?.name === NAVIGATORS.TAB_NAVIGATOR) {
navigationRef.current.dispatch({...minimalAction, type: CONST.NAVIGATION.ACTION_TYPE.POP_TO, target: targetState.key});
return;
}
navigationRef.current.dispatch({...StackActions.pop(distanceToPop), target: targetState.key});
}
/**
* Navigate back to the previous screen or a specified route.
* For detailed information about navigation patterns and best practices,
* see the NAVIGATION.md documentation.
* @param backToRoute - Fallback route if pop/goBack action should, but is not possible within RHP
* @param options - Optional configuration that affects navigation logic
*/
function goBack(backToRoute?: Route, options?: GoBackOptions) {
clearSelectedText();
if (!canNavigate('goBack', {backToRoute})) {
return;
}
const runImmediately = !options?.waitForTransition;
TransitionTracker.runAfterTransitions({
callback: () => {
if (backToRoute) {
goUp(backToRoute, options);
} else if (shouldPopToSidebar) {
popToSidebar();
} else if (!navigationRef.current?.canGoBack()) {
Log.hmmm('[Navigation] Unable to go back');
return;
} else {
navigationRef.current?.goBack();
}
if (options?.afterTransition) {
TransitionTracker.runAfterTransitions({callback: options.afterTransition, waitForUpcomingTransition: true});
}
},
runImmediately,
});
}
/**
* Navigate back to the sidebar screen in SplitNavigator and pop all central screens from the navigator at the same time.
* For detailed information about moving between screens,
* see the NAVIGATION.md documentation.
*/
function popToSidebar() {
setShouldPopToSidebar(false);
const rootState = navigationRef.current?.getRootState();
const currentRoute = rootState?.routes.at(-1);
if (!currentRoute) {
Log.hmmm('[popToSidebar] Unable to pop to sidebar, no current root found in navigator');
return;
}
// Split navigators can be nested inside TAB_NAVIGATOR → WORKSPACE_NAVIGATOR.
// Drill through the nesting to find the actual split navigator.
// Drill through TAB_NAVIGATOR → WORKSPACE_NAVIGATOR to find the active split navigator.
let activeRoute = currentRoute as typeof currentRoute | undefined;
if (currentRoute.name === NAVIGATORS.TAB_NAVIGATOR) {
const tabRoutes = currentRoute.state?.routes;
const activeTab = tabRoutes?.[currentRoute.state?.index ?? 0];
if (activeTab?.name === NAVIGATORS.WORKSPACE_NAVIGATOR) {
activeRoute = activeTab.state?.routes?.at(-1) as typeof currentRoute | undefined;
} else {
activeRoute = activeTab as typeof currentRoute | undefined;
}
}
if (!activeRoute || !isSplitNavigatorName(activeRoute.name)) {
Log.hmmm('[popToSidebar] must be invoked only from SplitNavigator');
return;
}
const topRoute = activeRoute.state?.routes.at(0);
const lastRoute = activeRoute.state?.routes.at(-1);
const currentRouteName = activeRoute.name as keyof typeof SPLIT_TO_SIDEBAR;
if (topRoute?.name !== SPLIT_TO_SIDEBAR[currentRouteName]) {
const params = activeRoute.name === NAVIGATORS.WORKSPACE_SPLIT_NAVIGATOR || activeRoute.name === NAVIGATORS.DOMAIN_SPLIT_NAVIGATOR ? {...lastRoute?.params} : undefined;
const sidebarName = SPLIT_TO_SIDEBAR[currentRouteName];
navigationRef.dispatch({payload: {name: sidebarName, params}, type: CONST.NAVIGATION.ACTION_TYPE.REPLACE});
return;
}
navigationRef.current?.dispatch(StackActions.popToTop());
}
/**
* Reset the navigation state to Home page.
*/
function resetToHome() {
clearFullscreenPreInsertedFlag();
const isNarrowLayout = getIsNarrowLayout();
const rootState = navigationRef.getRootState();
navigationRef.dispatch({...StackActions.popToTop(), target: rootState.key});
const splitNavigatorMainScreen = !isNarrowLayout
? {
name: SCREENS.REPORT,
}
: undefined;
const payload = getInitialSplitNavigatorState({name: SCREENS.INBOX}, splitNavigatorMainScreen);
navigationRef.dispatch({payload, type: CONST.NAVIGATION.ACTION_TYPE.REPLACE, target: rootState.key});
}
/**
* The goBack function doesn't support recursive pop e.g. pop route from root and then from nested navigator.
* There is only one case where recursive pop is needed which is going back to home.
* This function will cover this case.
* We will implement recursive pop if more use cases will appear.
*/
function goBackToHome() {
const isNarrowLayout = getIsNarrowLayout();
// This set the right split navigator.
goBack(ROUTES.HOME);
// We want to keep the report screen in the split navigator on wide layout.
if (!isNarrowLayout) {
return;
}
// This set the right route in this split navigator.
goBack(ROUTES.HOME);
}
/**
* Update route params for the specified route.
*
* @param targetKey - Optional navigator key to target the dispatch at. When provided,
* the SET_PARAMS action is delivered directly to that navigator, which is required for
* routes nested inside split navigators (where the default dispatch would fail if a
* modal is focused). Can be obtained via `navigation.getState()?.key` in a component.
*/
function setParams(params: Record<string, unknown>, routeKey = '', targetKey?: string) {
navigationRef.current?.dispatch({
...CommonActions.setParams(params),
source: routeKey,
...(targetKey && {target: targetKey}),
});
}
/**
* Returns the current active route without the URL params.
*/
function getActiveRouteWithoutParams(): string {
return getActiveRoute().replaceAll(/\?.*/g, '');
}
/**
* 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;
}
}
/**
* @private
* Navigate to the route that we originally intended to go to
* but the NavigationContainer was not ready when navigate() was called
*/
function goToPendingRoute() {
if (pendingNavigationCall === null) {
return;
}
Log.hmmm(`[Navigation] Container now ready, going to pending route: ${pendingNavigationCall.route}`);
navigate(pendingNavigationCall.route, pendingNavigationCall.options);
pendingNavigationCall = null;
}
function isNavigationReady(): Promise<void> {
return navigationIsReadyPromise;
}
function setIsNavigationReady() {
goToPendingRoute();
resolveNavigationIsReadyPromise();
}
/**
* @private
* 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 getReportRouteByID(reportID?: string, routes: NavigationRoute[] = navigationRef.getRootState().routes): NavigationRoute | null {
if (!reportID || !routes?.length) {
return null;
}
for (const route of routes) {
if (route.name === SCREENS.REPORT && !!route.params && 'reportID' in route.params && route.params.reportID === reportID) {
return route;
}
if (route.state?.routes) {
const partialRoute = getReportRouteByID(reportID, route.state.routes);
if (partialRoute) {
return partialRoute;
}
}
}
return null;
}
function getTopmostSuperWideRHPReportParams(
state: NavigationState = navigationRef.getRootState(),
): RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT] | RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.EXPENSE_REPORT] | undefined {
if (!state) {
return;
}
const topmostRightModalNavigator = state.routes?.at(-1);
if (topmostRightModalNavigator?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
return;
}
const topmostSuperWideRHP = topmostRightModalNavigator.state?.routes.findLast((route) => SUPER_WIDE_RIGHT_MODALS.has(route.name));
if (!topmostSuperWideRHP) {
return;
}
return topmostSuperWideRHP?.params as
| RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT]
| RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.EXPENSE_REPORT]
| undefined;
}
/**
* Get the report ID from the topmost Super Wide RHP modal in the navigation stack.
*/
function getTopmostSuperWideRHPReportID(state: NavigationState = navigationRef.getRootState()): string | undefined {
const topmostReportParams = getTopmostSuperWideRHPReportParams(state);
return topmostReportParams?.reportID;
}
/**
* Closes the modal navigator (RHP, onboarding).
*
* @param options - Configuration object
* @param options.ref - Navigation ref to use (defaults to navigationRef)
* @param options.afterTransition - Optional callback to execute after the navigation transition animation completes.
*
* For detailed information about dismissing modals,
* see the NAVIGATION.md documentation.
*/
function dismissModal({ref = navigationRef, afterTransition, waitForTransition}: {ref?: NavigationRef; afterTransition?: () => void; waitForTransition?: boolean} = {}) {
clearSelectedTextIfComposerBlurred();
const runImmediately = !waitForTransition;
const performDismiss = () => {
TransitionTracker.runAfterTransitions({
callback: () => {
ref.dispatch({type: CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL});
if (afterTransition) {
TransitionTracker.runAfterTransitions({callback: afterTransition, waitForUpcomingTransition: true});
}
},
runImmediately,
});
};
if (ref.isReady()) {
performDismiss();
} else {
isNavigationReady().then(performDismiss);
}
}
/**
* Dismisses the modal and opens the given report.
* For detailed information about dismissing modals,
* see the NAVIGATION.md documentation.
* @param options.onBeforeNavigate - Called before performing navigation with whether the report will be opened (true) or we only dismiss because already on that report (false).
*/
const dismissModalWithReport = (
{reportID, reportActionID, referrer, backTo}: ReportsSplitNavigatorParamList[typeof SCREENS.REPORT],
ref = navigationRef,
options?: {onBeforeNavigate?: (willOpenReport: boolean) => void},
) => {
const dismissAndOpenReport = () => {
const topmostSuperWideRHPReportID = getTopmostSuperWideRHPReportID();
let areReportsIDsDefined = !!topmostSuperWideRHPReportID && !!reportID;
if (topmostSuperWideRHPReportID === reportID && areReportsIDsDefined) {
options?.onBeforeNavigate?.(false);
dismissToSuperWideRHP();
return;
}
const topmostReportID = getTopmostReportId();
areReportsIDsDefined = !!topmostReportID && !!reportID;
const isReportsSplitTopmostFullScreen = isReportTopmostSplitNavigator();
if (topmostReportID === reportID && areReportsIDsDefined && isReportsSplitTopmostFullScreen) {
options?.onBeforeNavigate?.(false);
dismissModal();
return;
}
options?.onBeforeNavigate?.(true);
const reportRoute = ROUTES.REPORT_WITH_ID.getRoute(reportID, reportActionID, referrer, backTo);
dismissModal({
afterTransition: () => {
navigate(reportRoute);
},
});
};
if (ref.isReady()) {
dismissAndOpenReport();
} else {
isNavigationReady().then(dismissAndOpenReport);
}
};
function popRootToTop() {
const rootState = navigationRef.getRootState();
navigationRef.current?.dispatch({...StackActions.popToTop(), target: rootState.key});
}
function pop(target: string) {
navigationRef.current?.dispatch({...StackActions.pop(), target});
}
function removeScreenFromNavigationState(screen: string) {
isNavigationReady().then(() => {
navigationRef.current?.dispatch((state) => {
const routes = state.routes?.filter((item) => item.name !== screen);
return CommonActions.reset({
...state,
routes,
index: routes.length < state.routes.length ? state.index - 1 : state.index,
});
});
});
}
function isTopmostRouteModalScreen() {
const topmostRouteName = navigationRef.getRootState()?.routes?.at(-1)?.name;
return isSideModalNavigator(topmostRouteName);
}
function removeScreenByKey(key: string) {
isNavigationReady().then(() => {
navigationRef.current?.dispatch((state) => {
const routes = state.routes?.filter((item) => item.key !== key);
return CommonActions.reset({
...state,
routes,
index: routes.length < state.routes.length ? state.index - 1 : state.index,
});
});
});
}
function removeReportScreen(reportIDSet: Set<string>) {
isNavigationReady().then(() => {
navigationRef.current?.dispatch((state) => {
const routes = state?.routes.filter((route) => {
if (route.name === SCREENS.REPORT && route.params && 'reportID' in route.params) {
return !reportIDSet.has(route.params?.reportID as string);
}
return true;
});
return CommonActions.reset({
...state,
routes,
index: routes.length < state.routes.length ? state.index - 1 : state.index,
});
});
});
}
function isOnboardingFlow() {
const state = navigationRef.getRootState();
const currentFocusedRoute = findFocusedRoute(state);
return isOnboardingFlowName(currentFocusedRoute?.name);
}
function isValidateLoginFlow() {
const state = navigationRef.getRootState();
const currentFocusedRoute = findFocusedRoute(state);
return currentFocusedRoute?.name === SCREENS.VALIDATE_LOGIN;
}
function clearPreloadedRoutes() {
const rootStateWithoutPreloadedRoutes = {...navigationRef.getRootState(), preloadedRoutes: []} as NavigationState;
navigationRef.reset(rootStateWithoutPreloadedRoutes);
}
/**
* When multiple screens are open in RHP, returns to the last modal stack specified in the parameter. If none are found, it dismisses the entire modal.
*
* @param modalStackNames - names of the modal stacks we want to dismiss to
*/
function dismissToModalStack(modalStackNames: Set<string>, options: {afterTransition?: () => void} = {}) {
const rootState = navigationRef.getRootState();
if (!rootState) {
return;
}
const rhpState = rootState.routes.findLast((route) => route.name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR)?.state;
if (!rhpState) {
return;
}
const lastFoundModalStackIndex = rhpState.routes.slice(0, -1).findLastIndex((route) => modalStackNames.has(route.name));
const routesToPop = rhpState.routes.length - lastFoundModalStackIndex - 1;
if (routesToPop <= 0 || lastFoundModalStackIndex === -1) {
dismissModal(options);
return;
}
navigationRef.dispatch({...StackActions.pop(routesToPop), target: rhpState.key});
if (options?.afterTransition) {
TransitionTracker.runAfterTransitions({callback: options.afterTransition, waitForUpcomingTransition: true});
}
}
/**
* Dismiss top layer modal and go back to the Wide/Super Wide RHP.
*/
function dismissToPreviousRHP(options: {afterTransition?: () => void} = {}) {
return dismissToModalStack(ALL_WIDE_RIGHT_MODALS, options);
}
function navigateBackToLastSuperWideRHPScreen(options: {afterTransition?: () => void} = {}) {
return dismissToModalStack(SUPER_WIDE_RIGHT_MODALS, options);
}
function dismissToSuperWideRHP(options: {afterTransition?: () => void} = {}) {
navigateBackToLastSuperWideRHPScreen(options);
}
/**
* Reveals the destination fullscreen route under the currently open RHP before dismissing it.
* Used after expense submission (and similar flows) so the target screen (e.g. Search inside TabNavigator)
* is ready behind the modal: one dismiss animation instead of dismiss-then-navigate (two animations).
*
* Two-frame sequence:
* Frame 1 - REPLACE_FULLSCREEN_UNDER_RHP inserts the target fullscreen route underneath
* the modal (e.g. a new TabNavigator slice with Search selected): [Tab, RHP] -> [Tab, Tab', RHP].
* Browser history is NOT touched (the custom history extension preserves the old history array).
* Frame 2 - DISMISS_MODAL pops the RHP: [Tab, Tab', RHP] -> [Tab, Tab'].
* useLinking syncs browser history to the new top fullscreen route.
*/
function revealRouteBeforeDismissingModal(route: Route, options?: {afterTransition?: () => void}) {
if (!canNavigate('revealRouteBeforeDismissingModal', {route}) || !navigationRef.current) {
Log.hmmm(`[Navigation] Unable to reveal route before dismissing modal. Can't navigate.`, {route});