chore: migrate LoginView to hooks (#5092)

* chore: migrate LoginView to hooks

* minor tweak

* minor tweak

* fix ref

---------

Co-authored-by: GleidsonDaniel <gleidson10daniel@hotmail.com>
This commit is contained in:
Reinaldo Neto 2023-10-18 14:23:12 -03:00 committed by GitHub
parent c0660db06d
commit 3f2e5ced19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 251 additions and 266 deletions

View File

@ -3,7 +3,7 @@ import { Control, Controller } from 'react-hook-form';
import { FormTextInput, IRCTextInputProps } from './FormTextInput';
interface IControlledFormTextInputProps extends IRCTextInputProps {
interface IControlledFormTextInputProps extends Omit<IRCTextInputProps, 'inputRef'> {
control: Control<any>;
name: string;
}
@ -12,6 +12,8 @@ export const ControlledFormTextInput = ({ control, name, ...props }: IControlled
<Controller
control={control}
name={name}
render={({ field: { onChange, value } }) => <FormTextInput onChangeText={onChange} value={value} {...props} />}
render={({ field: { onChange, value, ref } }) => (
<FormTextInput onChangeText={onChange} value={value} inputRef={ref} {...props} />
)}
/>
);

View File

@ -1,264 +0,0 @@
import { dequal } from 'dequal';
import React from 'react';
import { Alert, Keyboard, StyleSheet, Text, View, TextInput as RNTextInput } from 'react-native';
import { connect } from 'react-redux';
import { loginRequest } from '../actions/login';
import { themes } from '../lib/constants';
import Button from '../containers/Button';
import FormContainer, { FormContainerInner } from '../containers/FormContainer';
import * as HeaderButton from '../containers/HeaderButton';
import LoginServices from '../containers/LoginServices';
import { FormTextInput } from '../containers/TextInput';
import { IApplicationState, IBaseScreen } from '../definitions';
import I18n from '../i18n';
import { OutsideParamList } from '../stacks/types';
import { withTheme } from '../theme';
import sharedStyles from './Styles';
import UGCRules from '../containers/UserGeneratedContentRules';
const styles = StyleSheet.create({
registerDisabled: {
...sharedStyles.textRegular,
...sharedStyles.textAlignCenter,
fontSize: 16
},
title: {
...sharedStyles.textBold,
fontSize: 22
},
inputContainer: {
marginVertical: 16
},
bottomContainer: {
flexDirection: 'column',
alignItems: 'center'
},
bottomContainerText: {
...sharedStyles.textRegular,
fontSize: 13
},
bottomContainerTextBold: {
...sharedStyles.textSemibold,
fontSize: 13
},
loginButton: {
marginTop: 16
},
ugcContainer: {
marginTop: 32
}
});
interface ILoginViewProps extends IBaseScreen<OutsideParamList, 'LoginView'> {
Site_Name: string;
Accounts_RegistrationForm: string;
Accounts_RegistrationForm_LinkReplacementText: string;
Accounts_EmailOrUsernamePlaceholder: string;
Accounts_PasswordPlaceholder: string;
Accounts_PasswordReset: boolean;
Accounts_ShowFormLogin: boolean;
isFetching: boolean;
error: {
error: string;
};
failure: boolean;
loginRequest: Function;
inviteLinkToken: string;
}
interface ILoginViewState {
user: string;
password: string;
}
class LoginView extends React.Component<ILoginViewProps, ILoginViewState> {
private passwordInput: RNTextInput | null | undefined;
static navigationOptions = ({ route, navigation }: ILoginViewProps) => ({
title: route?.params?.title ?? 'Rocket.Chat',
headerRight: () => <HeaderButton.Legal testID='login-view-more' navigation={navigation} />
});
constructor(props: ILoginViewProps) {
super(props);
this.state = {
user: props.route.params?.username ?? '',
password: ''
};
}
UNSAFE_componentWillReceiveProps(nextProps: ILoginViewProps) {
const { error } = this.props;
if (nextProps.failure && !dequal(error, nextProps.error)) {
if (nextProps.error?.error === 'error-invalid-email') {
this.resendEmailConfirmation();
} else {
Alert.alert(I18n.t('Oops'), I18n.t('Login_error'));
}
}
}
get showRegistrationButton() {
const { Accounts_RegistrationForm, inviteLinkToken } = this.props;
return Accounts_RegistrationForm === 'Public' || (Accounts_RegistrationForm === 'Secret URL' && inviteLinkToken?.length);
}
login = () => {
const { navigation, Site_Name } = this.props;
navigation.navigate('LoginView', { title: Site_Name });
};
register = () => {
const { navigation, Site_Name } = this.props;
navigation.navigate('RegisterView', { title: Site_Name });
};
forgotPassword = () => {
const { navigation, Site_Name } = this.props;
navigation.navigate('ForgotPasswordView', { title: Site_Name });
};
resendEmailConfirmation = () => {
const { user } = this.state;
const { navigation } = this.props;
navigation.navigate('SendEmailConfirmationView', { user });
};
valid = () => {
const { user, password } = this.state;
return user.trim() && password.trim();
};
submit = () => {
if (!this.valid()) {
return;
}
const { user, password } = this.state;
const { dispatch } = this.props;
Keyboard.dismiss();
dispatch(loginRequest({ user, password }));
};
renderUserForm = () => {
const { user } = this.state;
const {
Accounts_EmailOrUsernamePlaceholder,
Accounts_PasswordPlaceholder,
Accounts_PasswordReset,
Accounts_RegistrationForm_LinkReplacementText,
isFetching,
theme,
Accounts_ShowFormLogin
} = this.props;
if (!Accounts_ShowFormLogin) {
return null;
}
return (
<>
<Text style={[styles.title, sharedStyles.textBold, { color: themes[theme].titleText }]}>{I18n.t('Login')}</Text>
<FormTextInput
label={I18n.t('Username_or_email')}
containerStyle={styles.inputContainer}
placeholder={Accounts_EmailOrUsernamePlaceholder || I18n.t('Username_or_email')}
keyboardType='email-address'
returnKeyType='next'
onChangeText={(value: string) => this.setState({ user: value })}
onSubmitEditing={() => {
this.passwordInput?.focus();
}}
testID='login-view-email'
textContentType='username'
autoComplete='username'
value={user}
/>
<FormTextInput
label={I18n.t('Password')}
containerStyle={styles.inputContainer}
inputRef={e => {
this.passwordInput = e;
}}
placeholder={Accounts_PasswordPlaceholder || I18n.t('Password')}
returnKeyType='send'
secureTextEntry
onSubmitEditing={this.submit}
onChangeText={(value: string) => this.setState({ password: value })}
testID='login-view-password'
textContentType='password'
autoComplete='password'
/>
<Button
title={I18n.t('Login')}
type='primary'
onPress={this.submit}
testID='login-view-submit'
loading={isFetching}
disabled={!this.valid()}
style={styles.loginButton}
/>
{Accounts_PasswordReset && (
<Button
title={I18n.t('Forgot_password')}
type='secondary'
onPress={this.forgotPassword}
testID='login-view-forgot-password'
color={themes[theme].auxiliaryText}
fontSize={14}
/>
)}
{this.showRegistrationButton ? (
<View style={styles.bottomContainer}>
<Text style={[styles.bottomContainerText, { color: themes[theme].auxiliaryText }]}>
{I18n.t('Dont_Have_An_Account')}
</Text>
<Text
style={[styles.bottomContainerTextBold, { color: themes[theme].actionTintColor }]}
onPress={this.register}
testID='login-view-register'
>
{I18n.t('Create_account')}
</Text>
</View>
) : (
<Text style={[styles.registerDisabled, { color: themes[theme].auxiliaryText }]}>
{Accounts_RegistrationForm_LinkReplacementText}
</Text>
)}
<UGCRules styleContainer={styles.ugcContainer} />
</>
);
};
render() {
const { Accounts_ShowFormLogin } = this.props;
return (
<FormContainer testID='login-view'>
<FormContainerInner>
<LoginServices separator={Accounts_ShowFormLogin} />
{this.renderUserForm()}
</FormContainerInner>
</FormContainer>
);
}
}
const mapStateToProps = (state: IApplicationState) => ({
server: state.server.server,
Site_Name: state.settings.Site_Name as string,
Accounts_ShowFormLogin: state.settings.Accounts_ShowFormLogin as boolean,
Accounts_RegistrationForm: state.settings.Accounts_RegistrationForm as string,
Accounts_RegistrationForm_LinkReplacementText: state.settings.Accounts_RegistrationForm_LinkReplacementText as string,
isFetching: state.login.isFetching,
failure: state.login.failure,
error: state.login.error && state.login.error.data,
Accounts_EmailOrUsernamePlaceholder: state.settings.Accounts_EmailOrUsernamePlaceholder as string,
Accounts_PasswordPlaceholder: state.settings.Accounts_PasswordPlaceholder as string,
Accounts_PasswordReset: state.settings.Accounts_PasswordReset as boolean,
inviteLinkToken: state.inviteLinks.token
});
export default connect(mapStateToProps)(withTheme(LoginView));

View File

@ -0,0 +1,171 @@
import React, { useEffect } from 'react';
import { Keyboard, Text, View, Alert } from 'react-native';
import { useDispatch } from 'react-redux';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { loginRequest } from '../../actions/login';
import Button from '../../containers/Button';
import { ControlledFormTextInput } from '../../containers/TextInput';
import I18n from '../../i18n';
import { OutsideParamList } from '../../stacks/types';
import { useTheme } from '../../theme';
import sharedStyles from '../Styles';
import UGCRules from '../../containers/UserGeneratedContentRules';
import { useAppSelector } from '../../lib/hooks';
import styles from './styles';
interface ISubmit {
user: string;
password: string;
}
const schema = yup.object().shape({
user: yup.string().required(),
password: yup.string().required()
});
const UserForm = () => {
const { colors } = useTheme();
const dispatch = useDispatch();
const navigation = useNavigation<StackNavigationProp<OutsideParamList, 'LoginView'>>();
const {
params: { username }
} = useRoute<RouteProp<OutsideParamList, 'LoginView'>>();
const {
control,
handleSubmit,
formState: { isValid },
getValues,
setFocus
} = useForm<ISubmit>({ mode: 'onChange', resolver: yupResolver(schema), defaultValues: { user: username || '' } });
const {
Accounts_EmailOrUsernamePlaceholder,
Accounts_PasswordPlaceholder,
Accounts_PasswordReset,
Accounts_RegistrationForm_LinkReplacementText,
isFetching,
Accounts_RegistrationForm,
Site_Name,
inviteLinkToken,
error,
failure
} = useAppSelector(state => ({
Accounts_RegistrationForm: state.settings.Accounts_RegistrationForm as string,
Accounts_RegistrationForm_LinkReplacementText: state.settings.Accounts_RegistrationForm_LinkReplacementText as string,
isFetching: state.login.isFetching,
Accounts_EmailOrUsernamePlaceholder: state.settings.Accounts_EmailOrUsernamePlaceholder as string,
Accounts_PasswordPlaceholder: state.settings.Accounts_PasswordPlaceholder as string,
Accounts_PasswordReset: state.settings.Accounts_PasswordReset as boolean,
Site_Name: state.settings.Site_Name as string,
inviteLinkToken: state.inviteLinks.token,
failure: state.login.failure,
error: state.login.error && state.login.error.data
}));
useEffect(() => {
if (failure) {
if (error?.error === 'error-invalid-email') {
const user = getValues('user');
navigation.navigate('SendEmailConfirmationView', { user });
} else {
Alert.alert(I18n.t('Oops'), I18n.t('Login_error'));
}
}
}, [error?.error, failure, getValues, navigation]);
const showRegistrationButton =
Accounts_RegistrationForm === 'Public' || (Accounts_RegistrationForm === 'Secret URL' && inviteLinkToken?.length);
const register = () => {
navigation.navigate('RegisterView', { title: Site_Name });
};
const forgotPassword = () => {
navigation.navigate('ForgotPasswordView', { title: Site_Name });
};
const submit = ({ password, user }: ISubmit) => {
if (!isValid) {
return;
}
Keyboard.dismiss();
dispatch(loginRequest({ user, password }));
};
return (
<>
<Text style={[styles.title, sharedStyles.textBold, { color: colors.titleText }]}>{I18n.t('Login')}</Text>
<ControlledFormTextInput
name='user'
control={control}
label={I18n.t('Username_or_email')}
containerStyle={styles.inputContainer}
placeholder={Accounts_EmailOrUsernamePlaceholder || I18n.t('Username_or_email')}
keyboardType='email-address'
returnKeyType='next'
onSubmitEditing={() => setFocus('password')}
testID='login-view-email'
textContentType='username'
autoComplete='username'
/>
<ControlledFormTextInput
name='password'
control={control}
label={I18n.t('Password')}
containerStyle={styles.inputContainer}
placeholder={Accounts_PasswordPlaceholder || I18n.t('Password')}
returnKeyType='send'
secureTextEntry
onSubmitEditing={handleSubmit(submit)}
testID='login-view-password'
textContentType='password'
autoComplete='password'
/>
<Button
title={I18n.t('Login')}
type='primary'
onPress={handleSubmit(submit)}
testID='login-view-submit'
loading={isFetching}
disabled={!isValid}
style={styles.loginButton}
/>
{Accounts_PasswordReset ? (
<Button
title={I18n.t('Forgot_password')}
type='secondary'
onPress={forgotPassword}
testID='login-view-forgot-password'
color={colors.auxiliaryText}
fontSize={14}
/>
) : null}
{showRegistrationButton ? (
<View style={styles.bottomContainer}>
<Text style={[styles.bottomContainerText, { color: colors.auxiliaryText }]}>{I18n.t('Dont_Have_An_Account')}</Text>
<Text
style={[styles.bottomContainerTextBold, { color: colors.actionTintColor }]}
onPress={register}
testID='login-view-register'
>
{I18n.t('Create_account')}
</Text>
</View>
) : (
<Text style={[styles.registerDisabled, { color: colors.auxiliaryText }]}>
{Accounts_RegistrationForm_LinkReplacementText}
</Text>
)}
<UGCRules styleContainer={styles.ugcContainer} />
</>
);
};
export default UserForm;

View File

@ -0,0 +1,40 @@
import React, { useLayoutEffect } from 'react';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { useAppSelector } from '../../lib/hooks';
import FormContainer, { FormContainerInner } from '../../containers/FormContainer';
import * as HeaderButton from '../../containers/HeaderButton';
import LoginServices from '../../containers/LoginServices';
import { OutsideParamList } from '../../stacks/types';
import UserForm from './UserForm';
const LoginView = () => {
const navigation = useNavigation<StackNavigationProp<OutsideParamList, 'LoginView'>>();
const {
params: { title }
} = useRoute<RouteProp<OutsideParamList, 'LoginView'>>();
const { Accounts_ShowFormLogin } = useAppSelector(state => ({
Accounts_ShowFormLogin: state.settings.Accounts_ShowFormLogin as boolean
}));
useLayoutEffect(() => {
navigation.setOptions({
title: title ?? 'Rocket.Chat',
headerRight: () => <HeaderButton.Legal testID='login-view-more' navigation={navigation} />
});
}, [navigation, title]);
return (
<FormContainer testID='login-view'>
<FormContainerInner>
<LoginServices separator={Accounts_ShowFormLogin} />
{Accounts_ShowFormLogin ? <UserForm /> : null}
</FormContainerInner>
</FormContainer>
);
};
export default LoginView;

View File

@ -0,0 +1,36 @@
import { StyleSheet } from 'react-native';
import sharedStyles from '../Styles';
export default StyleSheet.create({
registerDisabled: {
...sharedStyles.textRegular,
...sharedStyles.textAlignCenter,
fontSize: 16
},
title: {
...sharedStyles.textBold,
fontSize: 22
},
inputContainer: {
marginVertical: 16
},
bottomContainer: {
flexDirection: 'column',
alignItems: 'center'
},
bottomContainerText: {
...sharedStyles.textRegular,
fontSize: 13
},
bottomContainerTextBold: {
...sharedStyles.textSemibold,
fontSize: 13
},
loginButton: {
marginTop: 16
},
ugcContainer: {
marginTop: 32
}
});