Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / hooks / useAliasForLoginModal.ts
blobcf85be34a163749c1ee595fe8b902fbb0f30ab6a
1 import { useEffect, useState } from 'react';
2 import { useSelector } from 'react-redux';
4 import type { FormikContextType } from 'formik';
6 import { selectAliasByAliasEmail } from '@proton/pass/store/selectors';
7 import type { LoginItemFormValues } from '@proton/pass/types';
8 import { merge } from '@proton/pass/utils/object/merge';
9 import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
11 import { useAliasOptions } from './useAliasOptions';
13 export const useAliasForLoginModal = <T extends LoginItemFormValues>(form: FormikContextType<T>) => {
14     const [aliasModalOpen, setAliasModalOpen] = useState(false);
16     const { values } = form;
17     const { withAlias, itemEmail, aliasPrefix } = values;
19     const aliasOptions = useAliasOptions({ shareId: form.values.shareId, lazy: true });
21     const relatedAlias = useSelector(selectAliasByAliasEmail(itemEmail));
22     const canCreateAlias = !relatedAlias && !withAlias;
23     const willCreateAlias = !relatedAlias && withAlias && !isEmptyString(aliasPrefix);
24     const usernameIsAlias = relatedAlias || willCreateAlias;
26     useEffect(() => {
27         if (relatedAlias) {
28             void form.setValues((values) =>
29                 merge(values, {
30                     withAlias: false,
31                     aliasPrefix: '',
32                     aliasSuffix: undefined,
33                     mailboxes: [],
34                 })
35             );
36         }
37     }, [relatedAlias]);
39     useEffect(() => {
40         if (aliasModalOpen) aliasOptions.request();
41     }, [aliasModalOpen]);
43     return {
44         setOpen: setAliasModalOpen,
45         open: aliasModalOpen,
46         relatedAlias,
47         canCreate: canCreateAlias,
48         willCreate: willCreateAlias,
49         usernameIsAlias,
50         aliasOptions: aliasOptions,
51     };