Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / pass / components / Form / Field / PasswordField.tsx
blob4784fa128b5518fa516797e1e51244cd2456b5e3
1 import { type FC, useCallback, useRef } from 'react';
3 import { PasswordGeneratorButton } from '@proton/pass/components/Password/PasswordGeneratorButton';
4 import {
5     strenghtIconNames,
6     strengthClassNames,
7     translateStrengths,
8 } from '@proton/pass/components/Password/PasswordStrength';
9 import { usePasswordStrength } from '@proton/pass/hooks/monitor/usePasswordStrength';
10 import clsx from '@proton/utils/clsx';
12 import { TextField, type TextFieldProps } from './TextField';
14 import './PasswordField.scss';
16 type Props = { onPasswordGenerated?: (password: string) => void; showStrength?: boolean } & TextFieldProps;
18 export const PasswordField: FC<Props> = (props) => {
19     const { field, form, onPasswordGenerated, label, showStrength, icon, className, ...rest } = props;
20     const passwordFieldRef = useRef<HTMLInputElement>(null);
22     const focusPasswordField = () => {
23         setTimeout(() => passwordFieldRef.current?.focus(), 300);
24     };
26     const passwordStrength = usePasswordStrength(form.values.password);
28     const handlePasswordGeneratorDone = useCallback(
29         async (password: string) => {
30             onPasswordGenerated?.(password);
31             await form.setFieldValue(field.name, password);
32             focusPasswordField();
33         },
34         [form, field.name, onPasswordGenerated]
35     );
37     const actions =
38         rest.actions !== null ? (
39             <PasswordGeneratorButton
40                 key="password-generator-button"
41                 onSubmit={handlePasswordGeneratorDone}
42                 tabIndex={-1}
43             />
44         ) : undefined;
46     return (
47         <TextField
48             className={passwordStrength ? clsx(className, strengthClassNames[passwordStrength]) : className}
49             icon={passwordStrength ? strenghtIconNames[passwordStrength] : icon}
50             label={passwordStrength ? `${label} ยท ${translateStrengths()[passwordStrength]}` : label}
51             hidden
52             field={field}
53             form={form}
54             {...rest}
55             actions={actions}
56             inputClassName={clsx('pass-password-field--input text-monospace', rest.inputClassName)}
57             ref={passwordFieldRef}
58         />
59     );