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],
22 ['notifications', NOTIFICATION_ID],
24 if (errors[errorId as keyof EventModelErrors]) {
25 focusInput(containerEl, formId);
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) => {
54 setLastAction(ACTION.SUBMIT);
55 if (handleValidation(errors, containerEl)) {
58 void withLoadingAction(onSave(inviteActions));
61 const handleDelete = (inviteActions: InviteActions) => {
62 setLastAction(ACTION.DELETE);
66 void withLoadingAction(onDelete(inviteActions));