Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / applications / calendar / src / app / hooks / useGetOpenedMailEvents.tsx
blobf1b38bee44f095c3a4a49e3e2f4d364537a6ce07
1 import { useCallback, useEffect, useRef } from 'react';
3 import { VIEWS } from '@proton/shared/lib/calendar/constants';
4 import { APPS } from '@proton/shared/lib/constants';
5 import { getIsDrawerPostMessage, postMessageFromIframe } from '@proton/shared/lib/drawer/helpers';
6 import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces';
8 const getIsMatch = (existingEvent: OpenedMailEvent, newEvent: OpenedMailEvent) => {
9     const { messageID: existingMessageID, UID: existingUID } = existingEvent;
10     const { messageID: newMessageID, UID: newUID } = newEvent;
12     return newMessageID === existingMessageID && newUID === existingUID;
15 export interface OpenedMailEvent {
16     messageID: string;
17     UID: string;
20 export const useGetOpenedMailEvents = (drawerView?: VIEWS): (() => OpenedMailEvent[]) => {
21     const isMailView = drawerView === VIEWS.MAIL;
22     const ref = useRef<OpenedMailEvent[]>([]);
24     useEffect(() => {
25         if (isMailView) {
26             // Ask Mail if calendar events are opened already
27             postMessageFromIframe({ type: DRAWER_EVENTS.REQUEST_OPEN_EVENTS }, APPS.PROTONMAIL);
28         }
29     }, [isMailView]);
31     useEffect(() => {
32         const handleMessageEvents = (event: MessageEvent) => {
33             if (!getIsDrawerPostMessage(event)) {
34                 return;
35             }
37             if (event.data.type === DRAWER_EVENTS.SET_WIDGET_EVENT) {
38                 const newOpenedMailEvent = event.data.payload;
39                 if (!ref.current.some((event) => getIsMatch(event, newOpenedMailEvent))) {
40                     ref.current.push({ ...newOpenedMailEvent });
41                 }
42             }
44             if (event.data.type === DRAWER_EVENTS.UNSET_WIDGET_EVENT) {
45                 const newOpenedMailEvent = event.data.payload;
46                 const index = ref.current.findIndex((event) => getIsMatch(event, newOpenedMailEvent));
47                 if (index !== -1) {
48                     ref.current.splice(index, 1);
49                 }
50             }
51         };
53         window.addEventListener('message', handleMessageEvents);
55         return () => {
56             window.removeEventListener('message', handleMessageEvents);
57         };
58     }, []);
60     return useCallback(() => {
61         return ref.current;
62     }, []);