Merge branch 'INDA-330-pii-update' into 'main'
[ProtonMail-WebClient.git] / applications / mail / src / app / hooks / useUnreadNotifications.tsx
blob0763acd5cc1940ae7e6c8afd78ddc720bb3fcb4f
1 import { useEffect, useMemo, useState } from 'react';
3 import { SECOND } from '@proton/shared/lib/constants';
4 import type { Message } from '@proton/shared/lib/interfaces/mail/Message';
5 import { isReceived } from '@proton/shared/lib/mail/messages';
7 /**
8  * Hook used to determine if we need to display the "X new unread messages" in the conversation view,
9  * which is a notification we display when we receive new incoming message while consulting a conversation
10  */
11 const useUnreadNotifications = (messages: Message[], conversationID: string) => {
12     // We are using a time marker to determine if we need to display unread notification or not.
13     // When opening the conversation, we set the timer to the current date.
14     // All new messages will be detected as new unread, and we will be able to display a notification.
15     // When reading a message we will move the time marker so that we display notifications for newer messages.
16     const [timeMarker, setTimeMarker] = useState(Date.now() / SECOND);
18     // We want to show the notification for messages that have been received after the current time marker
19     const unreadMessageAfterTimeMarkerIds = useMemo(() => {
20         const filteredMessages = messages.filter((message) => (message.Time || 0) > timeMarker && isReceived(message));
21         return filteredMessages.map((message) => message.ID);
22     }, [messages]);
24     // When reading a message, we can increase the time marker
25     const handleReadMessage = (messageID?: string) => {
26         // We want to set the time marker only if higher, otherwise, marking as read an older message would decrease
27         // the time marker (and potentially we would have to display more notifications)
28         const messageTime = messages.find((message) => message.ID === messageID)?.Time;
29         if (messageTime && messageTime > timeMarker) {
30             setTimeMarker(messageTime);
31         }
32     };
34     // Update the time marker when the conversation is updated
35     useEffect(() => {
36         setTimeMarker(Date.now() / SECOND);
37     }, [conversationID]);
39     return { unreadMessageAfterTimeMarkerIds, handleReadMessage };
42 export default useUnreadNotifications;