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 {
20 export const useGetOpenedMailEvents = (drawerView?: VIEWS): (() => OpenedMailEvent[]) => {
21 const isMailView = drawerView === VIEWS.MAIL;
22 const ref = useRef<OpenedMailEvent[]>([]);
26 // Ask Mail if calendar events are opened already
27 postMessageFromIframe({ type: DRAWER_EVENTS.REQUEST_OPEN_EVENTS }, APPS.PROTONMAIL);
32 const handleMessageEvents = (event: MessageEvent) => {
33 if (!getIsDrawerPostMessage(event)) {
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 });
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));
48 ref.current.splice(index, 1);
53 window.addEventListener('message', handleMessageEvents);
56 window.removeEventListener('message', handleMessageEvents);
60 return useCallback(() => {