Web: LoginMobile: refactoring

This commit is contained in:
Artem Tarasov 2021-02-19 14:06:38 +03:00
parent 6da8c9c0c4
commit feba30cb34
6 changed files with 32 additions and 320 deletions

View File

@ -1,21 +1,18 @@
import React, { Component, useEffect } from "react";
import styled, { css } from "styled-components";
import styled from "styled-components";
import { withTranslation } from "react-i18next";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
import { store, api, } from "ASC.Web.Common";
import { api } from "ASC.Web.Common";
import { Text, toastr } from "ASC.Web.Components";
import i18n from "../../../i18n";
import ForgotPasswordModalDialog from "./sub-components/forgot-password-modal-dialog";
import RegisterButton from "./sub-components/register-button";
import Header from "../../Header";
import LoginForm from "./sub-components/login-form";
const { login, setIsLoaded, reloadPortalSettings } = store.auth.actions;
const { getLanguage, isDesktopClient } = store.auth.selectors;
const { sendInstructionsToChangePassword } = api.people;
const { sendInstructionsToChangePassword } = api.people; //?
const LoginContainer = styled.div`
display: grid;
@ -144,27 +141,6 @@ class Form extends Component {
}
}
Form.propTypes = {
login: PropTypes.func, //.isRequired,
match: PropTypes.object, //.isRequired,
hashSettings: PropTypes.object,
reloadPortalSettings: PropTypes.func,
setIsLoaded: PropTypes.func, //.isRequired,
t: PropTypes.func, //.isRequired,
i18n: PropTypes.object, //.isRequired,
language: PropTypes.string, //.isRequired,
socialButtons: PropTypes.array,
organizationName: PropTypes.string,
homepage: PropTypes.string,
defaultPage: PropTypes.string,
};
Form.defaultProps = {
identifier: "",
password: "",
email: "",
};
const FormWrapper = withTranslation()(Form);
const Login = (props) => {
@ -181,13 +157,4 @@ const Login = (props) => {
);
};
Login.propTypes = {
language: PropTypes.string, //.isRequired,
isLoaded: PropTypes.bool,
enabledJoin: PropTypes.bool,
isDesktop: PropTypes.bool, //.isRequired,
};
export default withRouter(Login);

View File

@ -2,12 +2,12 @@ import React, { useState } from "react";
import styled from "styled-components";
import { Checkbox, Button, Link, Text } from "ASC.Web.Components";
import { checkPwd, utils } from "ASC.Web.Common";
import { utils } from "ASC.Web.Common";
import { PasswordField, EmailField } from "../../../fields";
import { PasswordField, TextField } from "../../../fields";
import { fakeApi } from "LoginMobileApi";
const { createPasswordHash, tryRedirectTo } = utils;
const { tryRedirectTo } = utils;
const StyledLoginForm = styled("form")`
width: 100%;
@ -68,24 +68,26 @@ const LoginForm = ({
const [password, setPassword] = useState("");
const [passwordValid, setPasswordValid] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError ] = useState(false)
const [hasError, setHasError] = useState(false);
const onSubmitHandler = () => {
errorText && setErrorText("");
let isError = false
const clearUserName = userName.trim();
let isError = false;
const cleanUserName = userName.trim();
if (!clearUserName) {
isError = true
setErrorText(t('RequiredFieldMessage'))
setHasError(isError)
if (!cleanUserName) {
isError = true;
setUserNameValid(false);
setErrorText(t("RequiredFieldMessage"));
setHasError(isError);
}
const clearPass = password.trim();
const cleanPass = password.trim();
if (!clearPass) {
isError = true
if (!cleanPass) {
isError = true;
setPasswordValid(false);
setErrorText(t("RequiredFieldMessage"));
setHasError(isError);
}
@ -94,7 +96,7 @@ const LoginForm = ({
setIsLoading(true);
fakeApi
.login(clearUserName, clearPass)
.login(cleanUserName, cleanPass)
.then(() => {
tryRedirectTo("/portal-selection");
})
@ -106,32 +108,28 @@ const LoginForm = ({
.finally(setIsLoading(false));
};
const onChangeLogin = (result) => {
const { value, isValid } = result;
const onChangeLogin = (value, isValid) => {
setUserName(value);
setUserNameValid(isValid);
setHasError(false)
//errors.length > 0 ? setErrorText(errors) : setErrorText(null);
};
const onChangePassword = (e) => {
setPassword(e.target.value);
!passwordValid && setPasswordValid(true);
errorText && setErrorText("");
setPasswordValid(true);
};
return (
<StyledLoginForm>
<EmailField
<TextField
t={t}
userNameValid={hasError}
hasError={!userNameValid}
errorText={errorText}
userName={userName}
value={userName}
isLoading={isLoading}
errorText={errorText}
onChangeLogin={onChangeLogin}
onKeyPress={onKeyPress}
id="email"
type="email"
placeholder="RegistrationEmailWatermark"
onChangeValue={onChangeLogin}
/>
<PasswordField
t={t}

View File

@ -1,127 +0,0 @@
import React, { useEffect, useState } from "react";
import Box from "@appserver/components/src/components/box";
import Text from "@appserver/components/src/components/text";
import toastr from "@appserver/components/src/components/toast/toastr";
import RegisterModalDialog from "./register-modal-dialog";
import styled from "styled-components";
import PropTypes from "prop-types";
import { sendRegisterRequest } from "@appserver/common/src/api/settings";
import { I18nextProvider, withTranslation } from "react-i18next";
import { getLanguage } from "@appserver/common/src/store/auth/selectors";
import { connect } from "react-redux";
import i18n from "../../../../i18n";
const StyledRegister = styled(Box)`
display: flex;
align-items: center;
justify-content: center;
z-index: 184;
width: 100%;
height: 66px;
padding: 1.5em;
bottom: 0;
right: 0;
background-color: #f8f9f9;
cursor: pointer;
`;
const Register = ({ t }) => {
const [visible, setVisible] = useState(false);
const [loading, setLoading] = useState(false);
const [email, setEmail] = useState("");
const [emailErr, setEmailErr] = useState(false);
const onRegisterClick = () => {
setVisible(true);
};
const onRegisterModalClose = () => {
setVisible(false);
setEmail("");
setEmailErr(false);
};
const onChangeEmail = (e) => {
setEmail(e.currentTarget.value);
setEmailErr(false);
};
const onSendRegisterRequest = () => {
if (!email.trim()) {
setEmailErr(true);
} else {
setLoading(true);
sendRegisterRequest(email)
.then(() => {
setLoading(false);
toastr.success("Successfully sent");
})
.catch((error) => {
setLoading(false);
toastr.error(error);
})
.finally(onRegisterModalClose);
}
};
return (
<>
<StyledRegister onClick={onRegisterClick}>
<Text color="#316DAA">{t("Register")}</Text>
</StyledRegister>
{visible && (
<RegisterModalDialog
visible={visible}
loading={loading}
email={email}
emailErr={emailErr}
t={t}
onChangeEmail={onChangeEmail}
onRegisterModalClose={onRegisterModalClose}
onSendRegisterRequest={onSendRegisterRequest}
/>
)}
</>
);
};
Register.propTypes = {
t: PropTypes.func.isRequired,
};
const RegisterTranslationWrapper = withTranslation()(Register);
const RegisterWrapper = (props) => {
const { language, isAuthenticated, enabledJoin } = props;
useEffect(() => {
i18n.changeLanguage(language);
}, [language]);
return (
<I18nextProvider i18n={i18n}>
{enabledJoin && !isAuthenticated && (
<RegisterTranslationWrapper {...props} />
)}
</I18nextProvider>
);
};
RegisterWrapper.propTypes = {
language: PropTypes.string,
isAuthenticated: PropTypes.bool,
enabledJoin: PropTypes.bool,
};
function mapStateToProps(state) {
const { isAuthenticated, settings } = state.auth;
const { enabledJoin } = settings;
return {
language: getLanguage(state),
isAuthenticated,
enabledJoin,
};
}
export default connect(mapStateToProps, null)(RegisterWrapper);

View File

@ -1,105 +0,0 @@
import React from "react";
import PropTypes from "prop-types";
import Button from "@appserver/components/src/components/button";
import TextInput from "@appserver/components/src/components/text-input";
import Text from "@appserver/components/src/components/text";
import ModalDialog from "@appserver/components/src/components/modal-dialog";
import FieldContainer from "@appserver/components/src/components/field-container";
import ModalDialogContainer from "./modal-dialog-container";
const domains = ["mail.ru", "gmail.com", "yandex.ru"];
const domainList = domains.map((domain, i) => (
<span key={i}>
<b>
{domain}
{i === domains.length - 1 ? "." : ", "}
</b>
</span>
));
const RegisterModalDialog = ({
visible,
loading,
email,
emailErr,
t,
onChangeEmail,
onRegisterModalClose,
onSendRegisterRequest,
}) => {
return (
<ModalDialogContainer>
<ModalDialog
visible={visible}
bodyPadding="16px 0 0 0"
onClose={onRegisterModalClose}
>
<ModalDialog.Header>
<Text isBold={true} fontSize="21px">
{t("RegisterTitle")}
</Text>
</ModalDialog.Header>
<ModalDialog.Body>
<Text key="text-body" isBold={false} fontSize="13px">
{t("RegisterTextBodyBeforeDomainsList")} {domainList}{" "}
{t("RegisterTextBodyAfterDomainsList")}
</Text>
<FieldContainer
key="e-mail"
isVertical={true}
hasError={emailErr}
labelVisible={false}
errorMessage={t("RequiredFieldMessage")}
>
<TextInput
hasError={emailErr}
placeholder={t("RegisterPlaceholder")}
isAutoFocussed={true}
id="e-mail"
name="e-mail"
type="text"
size="base"
scale={true}
tabIndex={3}
isDisabled={loading}
value={email}
onChange={onChangeEmail}
/>
</FieldContainer>
</ModalDialog.Body>
<ModalDialog.Footer>
<Button
className="modal-dialog-button"
key="SendBtn"
label={
loading ? t("RegisterProcessSending") : t("RegisterSendButton")
}
size="big"
scale={false}
primary={true}
onClick={onSendRegisterRequest}
isLoading={loading}
isDisabled={loading}
tabIndex={3}
/>
</ModalDialog.Footer>
</ModalDialog>
</ModalDialogContainer>
);
};
RegisterModalDialog.propTypes = {
visible: PropTypes.bool.isRequired,
loading: PropTypes.bool.isRequired,
email: PropTypes.string,
emailErr: PropTypes.bool.isRequired,
t: PropTypes.func.isRequired,
onChangeEmail: PropTypes.func.isRequired,
onSendRegisterRequest: PropTypes.func.isRequired,
onRegisterModalClose: PropTypes.func.isRequired,
};
export default RegisterModalDialog;

View File

@ -3,25 +3,14 @@
"LoginButton": "Sign In",
"Password": "Password",
"RegistrationEmailWatermark": "E-mail",
"MessageEmailConfirmed": "Your email was activated successfully.",
"MessageAuthorize": "Please authorize yourself.",
"ForgotPassword": "Forgot your password?",
"PasswordRecoveryTitle": "Password recovery",
"PasswordRecoveryPlaceholder": "Your registration e-mail",
"MessageSendPasswordRecoveryInstructionsOnEmail": "Please enter the email you used while registering on the portal. The password recovery instructions will be send to that email address.",
"RegisterTitle": "Registration request",
"RegisterTextBodyBeforeDomainsList": "Registration is available to users with an email account at",
"RegisterTextBodyAfterDomainsList": "To register, enter your email and click on Send request. An email message with a link to activate your account will be sent to the specified email. Please enter the email address where the invitation will be sent:",
"RegisterPlaceholder": "Your registration e-mail",
"RegisterSendButton": "Send request",
"RegisterProcessSending": "Sending...",
"SendButton": "Send",
"RequiredFieldMessage": "Required field",
"CancelButton": "Cancel",
"Remember": "Remember me",
"RememberHelper": "The default session lifetime is 20 minutes. Check this option to set it to 1 year. To set your own value, go to the settings.",
"CookieSettingsTitle": "Session Lifetime",
"Authorization": "Authorization",
"Or": "OR",
"Register": "Register",
"LoginTitle": "Sign in to your ONLYOFFICE cloud office",
@ -33,6 +22,6 @@
"LoginRegistrationBtn": "Register",
"RegistrationTitle": "Cloud office applications",
"RegistrationDesc": "Create portal",
"IncorrectEmail": "Incorrect email"
"IncorrectEmail": "Incorrect email",
"LengthPassLess": "Add {{lengthSetting}} characters"
}

View File

@ -3,25 +3,14 @@
"LoginButton": "Войти",
"Password": "Пароль",
"RegistrationEmailWatermark": "Регистрационный email",
"MessageEmailConfirmed": "Ваш email успешно активирован.",
"MessageAuthorize": "Пожалуйста авторизуйтесь.",
"ForgotPassword": "Забыли пароль?",
"PasswordRecoveryTitle": "Восстановление пароля",
"PasswordRecoveryPlaceholder": "Ваш регистрационный email",
"MessageSendPasswordRecoveryInstructionsOnEmail": "Пожалуйста, введите адрес электронной почты, указанный при регистрации на портале. Инструкции для восстановления пароля будут отправлены на этот адрес электронной почты.",
"RegisterTitle": "Запрос на регистрацию",
"RegisterTextBodyBeforeDomainsList": "Регистрация доступна для пользователей, которые имеют почтовый ящик на",
"RegisterTextBodyAfterDomainsList": "Чтобы зарегистрироваться, введите свой email и нажмите кнопку Отправить запрос. Сообщение со ссылкой для активации вашей учётной записи будет отправлено на указанный адрес.",
"RegisterPlaceholder": "Ваш регистрационный email",
"RegisterSendButton": "Отправить запрос",
"RegisterProcessSending": "Отправка...",
"SendButton": "Отправить",
"RequiredFieldMessage": "Обязательное поле",
"CancelButton": "Отмена",
"Remember": "Запомнить",
"RememberHelper": "Время существования сессии по умолчанию составляет 20 минут. Отметьте эту опцию, чтобы установить значение 1 год. Чтобы задать собственное значение, перейдите в настройки.",
"CookieSettingsTitle": "Время жизни сессии",
"Authorization": "Авторизация",
"Or": "ИЛИ",
"Register": "Регистрация",
"LoginTitle": "Войдите в облачный офис ONLYOFFICE",
@ -33,5 +22,6 @@
"LoginRegistrationBtn": "Регистрация",
"RegistrationTitle": "Облачные офисные приложения",
"RegistrationDesc": "Создать портал",
"IncorrectEmail": "Неверный email"
"IncorrectEmail": "Неверный email",
"LengthPassLess": "Добавьте {{lengthSetting}} символов"
}