Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TS migration] Migrate 'ValidateLogin' page to TypeScript #33839

26 changes: 13 additions & 13 deletions src/libs/Navigation/Navigation.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import {findFocusedRoute, getActionFromState} from '@react-navigation/core';
import {CommonActions, EventArg, getPathFromState, NavigationContainerEventMap, NavigationState, PartialState, StackActions} from '@react-navigation/native';
import { findFocusedRoute, getActionFromState } from '@react-navigation/core';
import { CommonActions, EventArg, getPathFromState, NavigationContainerEventMap, NavigationState, PartialState, StackActions } from '@react-navigation/native';
pac-guerreiro marked this conversation as resolved.
Show resolved Hide resolved
import findLastIndex from 'lodash/findLastIndex';
import Log from '@libs/Log';
import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import ROUTES, {Route} from '@src/ROUTES';
import SCREENS, {PROTECTED_SCREENS} from '@src/SCREENS';
import ROUTES, { Route } from '@src/ROUTES';
import SCREENS, { PROTECTED_SCREENS } from '@src/SCREENS';
import getStateFromPath from './getStateFromPath';
import originalGetTopmostReportActionId from './getTopmostReportActionID';
import originalGetTopmostReportId from './getTopmostReportId';
import linkingConfig from './linkingConfig';
import linkTo from './linkTo';
import navigationRef from './navigationRef';
import {StackNavigationAction, StateOrRoute} from './types';
import { StackNavigationAction, StateOrRoute } from './types';

let resolveNavigationIsReadyPromise: () => void;
const navigationIsReadyPromise = new Promise<void>((resolve) => {
Expand Down Expand Up @@ -82,7 +82,7 @@ function getDistanceFromPathInRootNavigator(path: string): number {
return index;
}

currentState = {...currentState, routes: currentState.routes.slice(0, -1), index: currentState.index - 1};
currentState = { ...currentState, routes: currentState.routes.slice(0, -1), index: currentState.index - 1 };
}

return -1;
Expand Down Expand Up @@ -123,7 +123,7 @@ function isActiveRoute(routePath: Route): boolean {
* @param [type] - Type of action to perform. Currently UP is supported.
*/
function navigate(route: Route = ROUTES.HOME, type?: string) {
if (!canNavigate('navigate', {route})) {
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}`);
Expand All @@ -138,7 +138,7 @@ function navigate(route: Route = ROUTES.HOME, type?: string) {
* @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) {
function goBack(fallbackRoute?: Route, shouldEnforceFallback = false, shouldPopToTop = false) {
if (!canNavigate('goBack')) {
return;
}
Expand Down Expand Up @@ -173,7 +173,7 @@ function goBack(fallbackRoute: Route, shouldEnforceFallback = false, shouldPopTo
}

const isCentralPaneFocused = findFocusedRoute(navigationRef.current.getState())?.name === NAVIGATORS.CENTRAL_PANE_NAVIGATOR;
const distanceFromPathInRootNavigator = getDistanceFromPathInRootNavigator(fallbackRoute);
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) {
Expand Down Expand Up @@ -228,9 +228,9 @@ function dismissModal(targetReportID?: string) {
} else if (targetReportID && rootState.routes.some((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});
navigationRef.current?.dispatch({ ...StackActions.pop(lastRouteIndex - centralRouteIndex), target: rootState.key });
} else {
navigationRef.current?.dispatch({...StackActions.pop(), target: rootState.key});
navigationRef.current?.dispatch({ ...StackActions.pop(), target: rootState.key });
}
break;
default: {
Expand Down Expand Up @@ -315,7 +315,7 @@ function waitForProtectedRoutes() {
return;
}

const unsubscribe = navigationRef.current?.addListener('state', ({data}) => {
const unsubscribe = navigationRef.current?.addListener('state', ({ data }) => {
const state = data?.state;
if (navContainsProtectedRoutes(state)) {
unsubscribe?.();
Expand Down Expand Up @@ -343,4 +343,4 @@ export default {
waitForProtectedRoutes,
};

export {navigationRef};
export { navigationRef };
61 changes: 0 additions & 61 deletions src/pages/ValidateLoginPage/index.js

This file was deleted.

42 changes: 42 additions & 0 deletions src/pages/ValidateLoginPage/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type {StackScreenProps} from '@react-navigation/stack';
import React, {useEffect} from 'react';
import {OnyxEntry, withOnyx} from 'react-native-onyx';
import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import Navigation from '@libs/Navigation/Navigation';
import type {AuthScreensParamList} from '@libs/Navigation/types';
import * as Session from '@userActions/Session';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';
import type {Session as SessionType} from '@src/types/onyx';

type ValidateLoginPageOnyxProps = {
session: OnyxEntry<SessionType>;
};

type ValidateLoginPageProps = ValidateLoginPageOnyxProps & StackScreenProps<AuthScreensParamList, typeof SCREENS.VALIDATE_LOGIN>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ValidateLoginPage has platform specific implementations, create types.ts file with a shared type

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! 👍


function ValidateLoginPage({
route: {
params: {accountID = '', validateCode = ''},
},
session,
}: ValidateLoginPageProps) {
useEffect(() => {
if (session?.authToken) {
// If already signed in, do not show the validate code if not on web,
// because we don't want to block the user with the interstitial page.
Navigation.goBack();
} else {
Session.signInWithValidateCodeAndNavigate(Number(accountID), validateCode);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return <FullScreenLoadingIndicator />;
}

ValidateLoginPage.displayName = 'ValidateLoginPage';

export default withOnyx<ValidateLoginPageProps, ValidateLoginPageOnyxProps>({
session: {key: ONYXKEYS.SESSION},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Credentials were removed, please test the component carefully on native

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@blazejkustra Credentials was not being used

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And honestly I don't know how to test this component on the native side because it seems this page is only used on web 🤷

})(ValidateLoginPage);
Original file line number Diff line number Diff line change
@@ -1,60 +1,34 @@
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import type {StackScreenProps} from '@react-navigation/stack';
import React, {useEffect} from 'react';
import {withOnyx} from 'react-native-onyx';
import {OnyxEntry, withOnyx} from 'react-native-onyx';
import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import ExpiredValidateCodeModal from '@components/ValidateCode/ExpiredValidateCodeModal';
import JustSignedInModal from '@components/ValidateCode/JustSignedInModal';
import ValidateCodeModal from '@components/ValidateCode/ValidateCodeModal';
import Navigation from '@libs/Navigation/Navigation';
import type {AuthScreensParamList} from '@libs/Navigation/types';
import * as Session from '@userActions/Session';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {defaultProps as validateLinkDefaultProps, propTypes as validateLinkPropTypes} from './validateLinkPropTypes';
import SCREENS from '@src/SCREENS';
import type {Account, Credentials, Session as SessionType} from '@src/types/onyx';

const propTypes = {
/** The accountID and validateCode are passed via the URL */
route: validateLinkPropTypes,

/** Session of currently logged in user */
session: PropTypes.shape({
/** Currently logged in user authToken */
authToken: PropTypes.string,
}),

/** The credentials of the person logging in */
credentials: PropTypes.shape({
/** The email the user logged in with */
login: PropTypes.string,

/** The validate code */
validateCode: PropTypes.string,
}),

/** The details about the account that the user is signing in with */
account: PropTypes.shape({
/** Whether a sign on form is loading (being submitted) */
isLoading: PropTypes.bool,
}),
type ValidateLoginPageOnyxProps = {
account: OnyxEntry<Account>;
credentials: OnyxEntry<Credentials>;
session: OnyxEntry<SessionType>;
};
pac-guerreiro marked this conversation as resolved.
Show resolved Hide resolved

const defaultProps = {
route: validateLinkDefaultProps,
session: {
authToken: null,
},
credentials: {},
account: {},
};
type ValidateLoginPageProps = ValidateLoginPageOnyxProps & StackScreenProps<AuthScreensParamList, typeof SCREENS.VALIDATE_LOGIN>;

function ValidateLoginPage(props) {
const login = lodashGet(props, 'credentials.login', null);
const autoAuthState = lodashGet(props, 'session.autoAuthState', CONST.AUTO_AUTH_STATE.NOT_STARTED);
const accountID = lodashGet(props.route.params, 'accountID', '');
const validateCode = lodashGet(props.route.params, 'validateCode', '');
const isSignedIn = Boolean(lodashGet(props, 'session.authToken', null));
const is2FARequired = lodashGet(props, 'account.requiresTwoFactorAuth', false);
const cachedAccountID = lodashGet(props, 'credentials.accountID', null);
function ValidateLoginPage({account, credentials, route, session}: ValidateLoginPageProps) {
const login = credentials?.login;
const autoAuthState = session?.autoAuthState ?? CONST.AUTO_AUTH_STATE.NOT_STARTED;
const accountID = Number(route?.params.accountID ?? '');
const validateCode = route.params.validateCode ?? '';
pac-guerreiro marked this conversation as resolved.
Show resolved Hide resolved
const isSignedIn = !!session?.authToken;
const is2FARequired = !!account?.requiresTwoFactorAuth;
const cachedAccountID = credentials?.accountID;

useEffect(() => {
if (!login && isSignedIn && (autoAuthState === CONST.AUTO_AUTH_STATE.SIGNING_IN || autoAuthState === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN)) {
Expand All @@ -74,7 +48,7 @@ function ValidateLoginPage(props) {
}, []);

useEffect(() => {
if (login || !cachedAccountID || !is2FARequired) {
if (!!login || !cachedAccountID || !is2FARequired) {
return;
}

Expand All @@ -98,11 +72,9 @@ function ValidateLoginPage(props) {
);
}

ValidateLoginPage.defaultProps = defaultProps;
ValidateLoginPage.displayName = 'ValidateLoginPage';
ValidateLoginPage.propTypes = propTypes;

export default withOnyx({
export default withOnyx<ValidateLoginPageProps, ValidateLoginPageOnyxProps>({
account: {key: ONYXKEYS.ACCOUNT},
credentials: {key: ONYXKEYS.CREDENTIALS},
session: {key: ONYXKEYS.SESSION},
Expand Down
Loading