-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AuthScreens.tsx
541 lines (495 loc) · 23.3 KB
/
AuthScreens.tsx
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
import React, {memo, useEffect, useMemo, useRef} from 'react';
import {View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import Onyx, {withOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import OptionsListContextProvider from '@components/OptionListContextProvider';
import useActiveWorkspace from '@hooks/useActiveWorkspace';
import useOnboardingLayout from '@hooks/useOnboardingLayout';
import usePermissions from '@hooks/usePermissions';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import {READ_COMMANDS} from '@libs/API/types';
import HttpUtils from '@libs/HttpUtils';
import KeyboardShortcut from '@libs/KeyboardShortcut';
import Log from '@libs/Log';
import getCurrentUrl from '@libs/Navigation/currentUrl';
import getOnboardingModalScreenOptions from '@libs/Navigation/getOnboardingModalScreenOptions';
import Navigation from '@libs/Navigation/Navigation';
import type {AuthScreensParamList, CentralPaneName, CentralPaneScreensParamList} from '@libs/Navigation/types';
import NetworkConnection from '@libs/NetworkConnection';
import * as Pusher from '@libs/Pusher/pusher';
import PusherConnectionManager from '@libs/PusherConnectionManager';
import * as ReportUtils from '@libs/ReportUtils';
import {buildSearchQueryString} from '@libs/SearchUtils';
import * as SessionUtils from '@libs/SessionUtils';
import ConnectionCompletePage from '@pages/ConnectionCompletePage';
import NotFoundPage from '@pages/ErrorPage/NotFoundPage';
import DesktopSignInRedirectPage from '@pages/signin/DesktopSignInRedirectPage';
import SearchInputManager from '@pages/workspace/SearchInputManager';
import * as App from '@userActions/App';
import * as Download from '@userActions/Download';
import * as Modal from '@userActions/Modal';
import * as PersonalDetails from '@userActions/PersonalDetails';
import * as PriorityMode from '@userActions/PriorityMode';
import * as Report from '@userActions/Report';
import * as Session from '@userActions/Session';
import toggleTestToolsModal from '@userActions/TestTool';
import Timing from '@userActions/Timing';
import * as User from '@userActions/User';
import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
import type * as OnyxTypes from '@src/types/onyx';
import type {SelectedTimezone, Timezone} from '@src/types/onyx/PersonalDetails';
import type ReactComponentModule from '@src/types/utils/ReactComponentModule';
import CENTRAL_PANE_SCREENS from './CENTRAL_PANE_SCREENS';
import createCustomStackNavigator from './createCustomStackNavigator';
import defaultScreenOptions from './defaultScreenOptions';
import getRootNavigatorScreenOptions from './getRootNavigatorScreenOptions';
import BottomTabNavigator from './Navigators/BottomTabNavigator';
import ExplanationModalNavigator from './Navigators/ExplanationModalNavigator';
import FeatureTrainingModalNavigator from './Navigators/FeatureTrainingModalNavigator';
import FullScreenNavigator from './Navigators/FullScreenNavigator';
import LeftModalNavigator from './Navigators/LeftModalNavigator';
import OnboardingModalNavigator from './Navigators/OnboardingModalNavigator';
import RightModalNavigator from './Navigators/RightModalNavigator';
import WelcomeVideoModalNavigator from './Navigators/WelcomeVideoModalNavigator';
type AuthScreensProps = {
/** Session of currently logged in user */
session: OnyxEntry<OnyxTypes.Session>;
/** The report ID of the last opened public room as anonymous user */
lastOpenedPublicRoomID: OnyxEntry<string>;
/** The last Onyx update ID was applied to the client */
initialLastUpdateIDAppliedToClient: OnyxEntry<number>;
};
const loadReportAttachments = () => require<ReactComponentModule>('../../../pages/home/report/ReportAttachments').default;
const loadValidateLoginPage = () => require<ReactComponentModule>('../../../pages/ValidateLoginPage').default;
const loadLogOutPreviousUserPage = () => require<ReactComponentModule>('../../../pages/LogOutPreviousUserPage').default;
const loadConciergePage = () => require<ReactComponentModule>('../../../pages/ConciergePage').default;
const loadTrackExpensePage = () => require<ReactComponentModule>('../../../pages/TrackExpensePage').default;
const loadSubmitExpensePage = () => require<ReactComponentModule>('../../../pages/SubmitExpensePage').default;
const loadProfileAvatar = () => require<ReactComponentModule>('../../../pages/settings/Profile/ProfileAvatar').default;
const loadWorkspaceAvatar = () => require<ReactComponentModule>('../../../pages/workspace/WorkspaceAvatar').default;
const loadReportAvatar = () => require<ReactComponentModule>('../../../pages/ReportAvatar').default;
const loadReceiptView = () => require<ReactComponentModule>('../../../pages/TransactionReceiptPage').default;
const loadWorkspaceJoinUser = () => require<ReactComponentModule>('@pages/workspace/WorkspaceJoinUserPage').default;
function shouldOpenOnAdminRoom() {
const url = getCurrentUrl();
return url ? new URL(url).searchParams.get('openOnAdminRoom') === 'true' : false;
}
function getCentralPaneScreenInitialParams(screenName: CentralPaneName, initialReportID?: string): Partial<ValueOf<CentralPaneScreensParamList>> {
if (screenName === SCREENS.SEARCH.CENTRAL_PANE) {
// Generate default query string with buildSearchQueryString without argument.
return {q: buildSearchQueryString(), isCustomQuery: false};
}
if (screenName === SCREENS.REPORT) {
return {
openOnAdminRoom: shouldOpenOnAdminRoom() ? true : undefined,
reportID: initialReportID,
};
}
return undefined;
}
let timezone: Timezone | null;
let currentAccountID = -1;
let isLoadingApp = false;
let lastUpdateIDAppliedToClient: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
// When signed out, val hasn't accountID
if (!(value && 'accountID' in value)) {
timezone = null;
return;
}
currentAccountID = value.accountID ?? -1;
if (Navigation.isActiveRoute(ROUTES.SIGN_IN_MODAL)) {
// This means sign in in RHP was successful, so we can subscribe to user events
User.subscribeToUserEvents();
}
},
});
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
if (!value || timezone) {
return;
}
timezone = value?.[currentAccountID]?.timezone ?? {};
const currentTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone as SelectedTimezone;
// If the current timezone is different than the user's timezone, and their timezone is set to automatic
// then update their timezone.
if (timezone?.automatic && timezone?.selected !== currentTimezone) {
timezone.selected = currentTimezone;
PersonalDetails.updateAutomaticTimezone({
automatic: true,
selected: currentTimezone,
});
}
},
});
Onyx.connect({
key: ONYXKEYS.IS_LOADING_APP,
callback: (value) => {
isLoadingApp = !!value;
},
});
Onyx.connect({
key: ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT,
callback: (value) => {
lastUpdateIDAppliedToClient = value;
},
});
function handleNetworkReconnect() {
if (isLoadingApp) {
App.openApp();
} else {
Log.info('[handleNetworkReconnect] Sending ReconnectApp');
App.reconnectApp(lastUpdateIDAppliedToClient);
}
}
const RootStack = createCustomStackNavigator<AuthScreensParamList>();
// We want to delay the re-rendering for components(e.g. ReportActionCompose)
// that depends on modal visibility until Modal is completely closed and its focused
// When modal screen is focused, update modal visibility in Onyx
// https://reactnavigation.org/docs/navigation-events/
const modalScreenListeners = {
focus: () => {
Modal.setModalVisibility(true);
},
blur: () => {
Modal.setModalVisibility(false);
},
beforeRemove: () => {
// Clear search input (WorkspaceInvitePage) when modal is closed
SearchInputManager.searchInput = '';
Modal.setModalVisibility(false);
Modal.willAlertModalBecomeVisible(false);
},
};
// Extended modal screen listeners with additional cancellation of pending requests
const modalScreenListenersWithCancelSearch = {
...modalScreenListeners,
beforeRemove: () => {
modalScreenListeners.beforeRemove();
HttpUtils.cancelPendingRequests(READ_COMMANDS.SEARCH_FOR_REPORTS);
},
};
function AuthScreens({session, lastOpenedPublicRoomID, initialLastUpdateIDAppliedToClient}: AuthScreensProps) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {isSmallScreenWidth} = useWindowDimensions();
const {isMediumOrLargerScreenWidth} = useOnboardingLayout();
const screenOptions = getRootNavigatorScreenOptions(isSmallScreenWidth, styles, StyleUtils);
const {canUseDefaultRooms} = usePermissions();
const {activeWorkspaceID} = useActiveWorkspace();
const onboardingModalScreenOptions = useMemo(() => screenOptions.onboardingModalNavigator(isMediumOrLargerScreenWidth), [screenOptions, isMediumOrLargerScreenWidth]);
const onboardingScreenOptions = useMemo(
() => getOnboardingModalScreenOptions(isSmallScreenWidth, styles, StyleUtils, isMediumOrLargerScreenWidth),
[StyleUtils, isSmallScreenWidth, isMediumOrLargerScreenWidth, styles],
);
let initialReportID: string | undefined;
const isInitialRender = useRef(true);
if (isInitialRender.current) {
Timing.start(CONST.TIMING.HOMEPAGE_INITIAL_RENDER);
const currentURL = getCurrentUrl();
if (currentURL) {
initialReportID = new URL(currentURL).pathname.match(CONST.REGEX.REPORT_ID_FROM_PATH)?.at(1);
}
if (!initialReportID) {
const initialReport = ReportUtils.findLastAccessedReport(!canUseDefaultRooms, shouldOpenOnAdminRoom(), activeWorkspaceID);
initialReportID = initialReport?.reportID ?? '';
}
isInitialRender.current = false;
}
useEffect(() => {
const shortcutsOverviewShortcutConfig = CONST.KEYBOARD_SHORTCUTS.SHORTCUTS;
const searchShortcutConfig = CONST.KEYBOARD_SHORTCUTS.SEARCH;
const chatShortcutConfig = CONST.KEYBOARD_SHORTCUTS.NEW_CHAT;
const debugShortcutConfig = CONST.KEYBOARD_SHORTCUTS.DEBUG;
const currentUrl = getCurrentUrl();
const isLoggingInAsNewUser = !!session?.email && SessionUtils.isLoggingInAsNewUser(currentUrl, session.email);
// Sign out the current user if we're transitioning with a different user
const isTransitioning = currentUrl.includes(ROUTES.TRANSITION_BETWEEN_APPS);
const isSupportalTransition = currentUrl.includes('authTokenType=support');
if (isLoggingInAsNewUser && isTransitioning) {
Session.signOutAndRedirectToSignIn(false, isSupportalTransition);
return;
}
NetworkConnection.listenForReconnect();
NetworkConnection.onReconnect(handleNetworkReconnect);
PusherConnectionManager.init();
Pusher.init({
appKey: CONFIG.PUSHER.APP_KEY,
cluster: CONFIG.PUSHER.CLUSTER,
authEndpoint: `${CONFIG.EXPENSIFY.DEFAULT_API_ROOT}api/AuthenticatePusher?`,
}).then(() => {
User.subscribeToUserEvents();
});
// If we are on this screen then we are "logged in", but the user might not have "just logged in". They could be reopening the app
// or returning from background. If so, we'll assume they have some app data already and we can call reconnectApp() instead of openApp().
if (SessionUtils.didUserLogInDuringSession()) {
App.openApp();
} else {
Log.info('[AuthScreens] Sending ReconnectApp');
App.reconnectApp(initialLastUpdateIDAppliedToClient);
}
PriorityMode.autoSwitchToFocusMode();
App.setUpPoliciesAndNavigate(session);
App.redirectThirdPartyDesktopSignIn();
if (lastOpenedPublicRoomID) {
// Re-open the last opened public room if the user logged in from a public room link
Report.openLastOpenedPublicRoom(lastOpenedPublicRoomID);
}
Download.clearDownloads();
Timing.end(CONST.TIMING.HOMEPAGE_INITIAL_RENDER);
// Listen to keyboard shortcuts for opening certain pages
const unsubscribeShortcutsOverviewShortcut = KeyboardShortcut.subscribe(
shortcutsOverviewShortcutConfig.shortcutKey,
() => {
Modal.close(() => {
if (Navigation.isActiveRoute(ROUTES.KEYBOARD_SHORTCUTS)) {
return;
}
return Navigation.navigate(ROUTES.KEYBOARD_SHORTCUTS);
});
},
shortcutsOverviewShortcutConfig.descriptionKey,
shortcutsOverviewShortcutConfig.modifiers,
true,
);
// Listen for the key K being pressed so that focus can be given to
// the chat switcher, or new group chat
// based on the key modifiers pressed and the operating system
const unsubscribeSearchShortcut = KeyboardShortcut.subscribe(
searchShortcutConfig.shortcutKey,
() => {
Modal.close(Session.checkIfActionIsAllowed(() => Navigation.navigate(ROUTES.CHAT_FINDER)));
},
shortcutsOverviewShortcutConfig.descriptionKey,
shortcutsOverviewShortcutConfig.modifiers,
true,
);
const unsubscribeChatShortcut = KeyboardShortcut.subscribe(
chatShortcutConfig.shortcutKey,
() => {
Modal.close(Session.checkIfActionIsAllowed(() => Navigation.navigate(ROUTES.NEW)));
},
chatShortcutConfig.descriptionKey,
chatShortcutConfig.modifiers,
true,
);
const unsubscribeDebugShortcut = KeyboardShortcut.subscribe(
debugShortcutConfig.shortcutKey,
() => {
toggleTestToolsModal();
},
debugShortcutConfig.descriptionKey,
debugShortcutConfig.modifiers,
true,
);
return () => {
unsubscribeShortcutsOverviewShortcut();
unsubscribeSearchShortcut();
unsubscribeChatShortcut();
unsubscribeDebugShortcut();
Session.cleanupSession();
};
// Rule disabled because this effect is only for component did mount & will component unmount lifecycle event
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, []);
const CentralPaneScreenOptions = {
headerShown: false,
title: 'New Expensify',
// Prevent unnecessary scrolling
cardStyle: styles.cardStyleNavigator,
};
return (
<OptionsListContextProvider>
<View style={styles.rootNavigatorContainerStyles(isSmallScreenWidth)}>
<RootStack.Navigator
screenOptions={screenOptions.centralPaneNavigator}
isSmallScreenWidth={isSmallScreenWidth}
>
<RootStack.Screen
name={NAVIGATORS.BOTTOM_TAB_NAVIGATOR}
options={screenOptions.bottomTab}
component={BottomTabNavigator}
/>
<RootStack.Screen
name={SCREENS.VALIDATE_LOGIN}
options={{
...screenOptions.fullScreen,
headerShown: false,
title: 'New Expensify',
}}
getComponent={loadValidateLoginPage}
/>
<RootStack.Screen
name={SCREENS.TRANSITION_BETWEEN_APPS}
options={defaultScreenOptions}
getComponent={loadLogOutPreviousUserPage}
/>
<RootStack.Screen
name={SCREENS.CONCIERGE}
options={defaultScreenOptions}
getComponent={loadConciergePage}
/>
<RootStack.Screen
name={SCREENS.TRACK_EXPENSE}
options={defaultScreenOptions}
getComponent={loadTrackExpensePage}
/>
<RootStack.Screen
name={SCREENS.SUBMIT_EXPENSE}
options={defaultScreenOptions}
getComponent={loadSubmitExpensePage}
/>
<RootStack.Screen
name={SCREENS.ATTACHMENTS}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
getComponent={loadReportAttachments}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.PROFILE_AVATAR}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
getComponent={loadProfileAvatar}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.WORKSPACE_AVATAR}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
getComponent={loadWorkspaceAvatar}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.REPORT_AVATAR}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
getComponent={loadReportAvatar}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.NOT_FOUND}
options={screenOptions.fullScreen}
component={NotFoundPage}
/>
<RootStack.Screen
name={NAVIGATORS.RIGHT_MODAL_NAVIGATOR}
options={screenOptions.rightModalNavigator}
component={RightModalNavigator}
listeners={modalScreenListenersWithCancelSearch}
/>
<RootStack.Screen
name={NAVIGATORS.FULL_SCREEN_NAVIGATOR}
options={screenOptions.fullScreen}
component={FullScreenNavigator}
/>
<RootStack.Screen
name={NAVIGATORS.LEFT_MODAL_NAVIGATOR}
options={screenOptions.leftModalNavigator}
component={LeftModalNavigator}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.DESKTOP_SIGN_IN_REDIRECT}
options={screenOptions.fullScreen}
component={DesktopSignInRedirectPage}
/>
<RootStack.Screen
name={NAVIGATORS.EXPLANATION_MODAL_NAVIGATOR}
options={onboardingModalScreenOptions}
component={ExplanationModalNavigator}
/>
<RootStack.Screen
name={NAVIGATORS.FEATURE_TRANING_MODAL_NAVIGATOR}
options={onboardingModalScreenOptions}
component={FeatureTrainingModalNavigator}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={NAVIGATORS.WELCOME_VIDEO_MODAL_NAVIGATOR}
options={onboardingModalScreenOptions}
component={WelcomeVideoModalNavigator}
/>
<RootStack.Screen
name={NAVIGATORS.ONBOARDING_MODAL_NAVIGATOR}
options={onboardingScreenOptions}
component={OnboardingModalNavigator}
listeners={{
focus: () => {
Modal.setDisableDismissOnEscape(true);
},
beforeRemove: () => Modal.setDisableDismissOnEscape(false),
}}
/>
<RootStack.Screen
name={SCREENS.WORKSPACE_JOIN_USER}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
listeners={modalScreenListeners}
getComponent={loadWorkspaceJoinUser}
/>
<RootStack.Screen
name={SCREENS.TRANSACTION_RECEIPT}
options={{
headerShown: false,
presentation: 'transparentModal',
}}
getComponent={loadReceiptView}
listeners={modalScreenListeners}
/>
<RootStack.Screen
name={SCREENS.CONNECTION_COMPLETE}
options={defaultScreenOptions}
component={ConnectionCompletePage}
/>
{Object.entries(CENTRAL_PANE_SCREENS).map(([screenName, componentGetter]) => {
const centralPaneName = screenName as CentralPaneName;
return (
<RootStack.Screen
key={centralPaneName}
name={centralPaneName}
initialParams={getCentralPaneScreenInitialParams(centralPaneName, initialReportID)}
getComponent={componentGetter}
options={CentralPaneScreenOptions}
/>
);
})}
</RootStack.Navigator>
</View>
</OptionsListContextProvider>
);
}
AuthScreens.displayName = 'AuthScreens';
const AuthScreensMemoized = memo(AuthScreens, () => true);
export default withOnyx<AuthScreensProps, AuthScreensProps>({
session: {
key: ONYXKEYS.SESSION,
},
lastOpenedPublicRoomID: {
key: ONYXKEYS.LAST_OPENED_PUBLIC_ROOM_ID,
},
initialLastUpdateIDAppliedToClient: {
key: ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT,
},
})(AuthScreensMemoized);