import React from 'react'; import { Form, Field, FormApi } from 'react-final-form'; import { OnChange } from 'react-final-form-listeners'; import { useTranslation } from 'react-i18next'; import Button from '@mui/material/Button'; import Checkbox from '@mui/material/Checkbox'; import CircularProgress from '@mui/material/CircularProgress'; import FormControlLabel from '@mui/material/FormControlLabel'; import { CheckboxField, InputField, KnownHosts } from '@app/components'; import type { FormErrors } from '@app/forms'; import { LoadingState, useKnownHosts, useSettings } from '@app/hooks'; import { HostDTO } from '@app/services'; import { useLoginFormBody } from './useLoginForm'; import './LoginForm.css'; export interface LoginFormValues { userName: string; password: string; remember: boolean; autoConnect: boolean; selectedHost: HostDTO; } interface LoginFormProps { onSubmit: (values: LoginFormValues) => void; disableSubmitButton: boolean; onResetPassword: () => void; } interface LoginFormBodyProps extends LoginFormProps { form: FormApi; handleSubmit: (event?: React.SyntheticEvent) => void; } const LoginFormBody = ({ form, handleSubmit, disableSubmitButton, onResetPassword, }: LoginFormBodyProps) => { const { t } = useTranslation(); const PASSWORD_LABEL = t('Common.label.password'); const STORED_PASSWORD_LABEL = t('LoginForm.label.savedPassword'); const { useStoredPasswordLabel, setUseStoredPasswordLabel, onSelectedHostChange, onUserNameChange, onRememberChange, onUserToggleAutoConnect, passwordFieldBlur, } = useLoginFormBody(form); return (
{onUserNameChange}
setUseStoredPasswordLabel(false)} onBlur={passwordFieldBlur} name="password" type="password" component={InputField} autoComplete="new-password" />
{onRememberChange}
{onSelectedHostChange}
{({ input }) => ( onUserToggleAutoConnect(checked, input.onChange)} color="primary" /> } /> )}
); }; const LoginForm = (props: LoginFormProps) => { const { t } = useTranslation(); const knownHosts = useKnownHosts(); const settings = useSettings(); const validate = (values: Partial): FormErrors => { const errors: FormErrors = {}; if (!values.userName) { errors.userName = t('Common.validation.required'); } if (!values.selectedHost) { errors.selectedHost = t('Common.validation.required'); } return errors; }; const handleOnSubmit = ({ userName, ...values }: LoginFormValues) => { props.onSubmit({ ...values, userName: userName?.trim() }); }; if (knownHosts.status !== LoadingState.READY || settings.status !== LoadingState.READY) { return (
); } const selectedHost = knownHosts.value?.selectedHost; const initialValues: Partial = { selectedHost, userName: selectedHost?.userName ?? '', remember: Boolean(selectedHost?.remember), autoConnect: Boolean(settings.value?.autoConnect), password: '', }; return (
{({ handleSubmit, form }) => ( )} ); }; export default LoginForm;