Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / applications / calendar / src / app / components / eventModal / hooks / useForm.tsx
blob9144e451bd47856c121f252369afffbd0b26912a
1 import { useState } from 'react';
3 import { NOTIFICATION_ID } from '@proton/components';
4 import { useLoading } from '@proton/hooks';
5 import { TITLE_INPUT_ID } from '@proton/shared/lib/calendar/constants';
6 import type { EventModelErrors } from '@proton/shared/lib/interfaces/calendar';
7 import isTruthy from '@proton/utils/isTruthy';
9 import type { InviteActions } from '../../../interfaces/Invite';
10 import { COUNT_ID, UNTIL_ID } from '../rows/EndsRow';
12 const focusInput = (el: HTMLElement | null, id: string) => {
13     el?.querySelector<HTMLInputElement>(`#${id}`)?.focus();
16 const handleValidation = (errors: EventModelErrors, containerEl: HTMLElement | null) => {
17     if (Object.values(errors).filter(isTruthy).length > 0) {
18         for (const [errorId, formId] of [
19             ['title', TITLE_INPUT_ID],
20             ['until', UNTIL_ID],
21             ['count', COUNT_ID],
22             ['notifications', NOTIFICATION_ID],
23         ]) {
24             if (errors[errorId as keyof EventModelErrors]) {
25                 focusInput(containerEl, formId);
26                 return true;
27             }
28         }
30         return true;
31     }
32     return false;
35 export enum ACTION {
36     SUBMIT,
37     DELETE,
40 interface Arguments {
41     containerEl: HTMLElement | null;
42     errors: EventModelErrors;
43     onSave: (inviteActions: InviteActions) => Promise<void>;
44     onDelete?: (inviteActions: InviteActions) => Promise<void>;
47 export const useForm = ({ containerEl, errors, onSave, onDelete }: Arguments) => {
48     const [isSubmitted, setIsSubmitted] = useState(false);
49     const [loadingAction, withLoadingAction] = useLoading();
50     const [lastAction, setLastAction] = useState<ACTION | null>(null);
52     const handleSubmit = (inviteActions: InviteActions) => {
53         setIsSubmitted(true);
54         setLastAction(ACTION.SUBMIT);
55         if (handleValidation(errors, containerEl)) {
56             return;
57         }
58         void withLoadingAction(onSave(inviteActions));
59     };
61     const handleDelete = (inviteActions: InviteActions) => {
62         setLastAction(ACTION.DELETE);
63         if (!onDelete) {
64             return;
65         }
66         void withLoadingAction(onDelete(inviteActions));
67     };
69     return {
70         isSubmitted,
71         loadingAction,
72         handleDelete,
73         handleSubmit,
74         lastAction,
75     };