ente/src/components/SingleInputForm.tsx

102 lines
3.4 KiB
TypeScript
Raw Normal View History

2021-05-30 16:56:48 +00:00
import React, { useState } from 'react';
import constants from 'utils/strings/constants';
2021-05-30 16:56:48 +00:00
import { Form } from 'react-bootstrap';
import { Formik, FormikHelpers } from 'formik';
import * as Yup from 'yup';
import SubmitButton from './SubmitButton';
2021-08-03 20:38:34 +00:00
import styled from 'styled-components';
import Visibility from './icons/Visibility';
import VisibilityOff from './icons/VisibilityOff';
interface formValues {
passphrase: string;
}
interface Props {
callback: (passphrase: string, setFieldError) => void;
fieldType: string;
placeholder: string;
buttonText: string;
}
2021-08-06 20:39:16 +00:00
const Group = styled.div`
position: relative;
2021-08-03 20:38:34 +00:00
`;
const Button = styled.button`
background: transparent;
border: none;
2021-08-06 20:52:08 +00:00
width: 46px;
2021-08-06 20:39:16 +00:00
height: 34px;
position: absolute;
top: 1px;
right: 1px;
border-radius: 5px;
2021-08-03 20:38:34 +00:00
align-items: center;
`;
export default function SingleInputForm(props: Props) {
const [loading, SetLoading] = useState(false);
2021-08-03 20:38:34 +00:00
const [showPassword, setShowPassword] = useState(false);
const submitForm = async (
values: formValues,
2021-08-13 02:38:38 +00:00
{ setFieldError }: FormikHelpers<formValues>
) => {
SetLoading(true);
await props.callback(values.passphrase, setFieldError);
SetLoading(false);
};
return (
<Formik<formValues>
2021-05-30 16:56:48 +00:00
initialValues={{ passphrase: '' }}
onSubmit={submitForm}
validationSchema={Yup.object().shape({
passphrase: Yup.string().required(constants.REQUIRED),
})}
validateOnChange={false}
2021-08-13 02:38:38 +00:00
validateOnBlur={false}>
{({ values, touched, errors, handleChange, handleSubmit }) => (
<Form noValidate onSubmit={handleSubmit}>
2021-08-06 20:39:16 +00:00
<Form.Group>
<Group>
<Form.Control
type={showPassword ? 'text' : props.fieldType}
placeholder={props.placeholder}
value={values.passphrase}
onChange={handleChange('passphrase')}
isInvalid={Boolean(
2021-08-13 02:38:38 +00:00
touched.passphrase && errors.passphrase
2021-08-06 20:39:16 +00:00
)}
disabled={loading}
autoFocus
/>
2021-08-13 02:38:38 +00:00
{props.fieldType === 'password' && (
<Button
type="button"
onClick={() =>
setShowPassword(!showPassword)
}>
{showPassword ? (
<VisibilityOff />
) : (
<Visibility />
)}
2021-08-03 20:38:34 +00:00
</Button>
2021-08-13 02:38:38 +00:00
)}
2021-08-06 20:39:16 +00:00
<Form.Control.Feedback type="invalid">
{errors.passphrase}
</Form.Control.Feedback>
</Group>
</Form.Group>
<SubmitButton
buttonText={props.buttonText}
loading={loading}
/>
<br />
</Form>
)}
</Formik>
);
}