Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3101 stevensc 1
import React from "react";
1 www 2
import { useState, useEffect } from "react";
976 stevensc 3
import { axios } from "../../utils";
1 www 4
import Contacts from "./contacts/Contacts";
1335 stevensc 5
import NotificationAlert from "../../shared/notification/NotificationAlert";
1 www 6
import Groups from "./groups/Groups";
7
import PersonalChat from "./personal-chat/PersonalChat";
2739 stevensc 8
import { FiMaximize2 } from 'react-icons/fi'
1 www 9
 
10
const notifyAudio = new Audio("/audio/chat.mp3");
11
 
12
const Chat = (props) => {
3101 stevensc 13
 
1 www 14
  // states
15
  const [contacts, setContacts] = useState([]);
16
  const [groups, setGroups] = useState([]);
17
  const [activeChats, setActiveChats] = useState([]);
18
  const [isChatOpen, setIsChatOpen] = useState(false);
19
  const [isMuted, setIsMuted] = useState(false);
20
  const [activeTab, setActiveTab] = useState("user");
976 stevensc 21
  const [search, setSearch] = useState('');
1775 stevensc 22
  const [loading, setLoading] = useState(false);
976 stevensc 23
 
994 stevensc 24
  const filtredContacts = contacts.filter(({ name }) => name.toLowerCase().includes(search.toLowerCase()))
25
  const filtredGroups = groups.filter(({ name }) => name.toLowerCase().includes(search.toLowerCase()))
976 stevensc 26
 
27
  const handleEntities = entities => {
687 steven 28
    let newUserContacts = [];
29
    let newGroups = [];
30
    entities.map((entity) => {
3111 stevensc 31
      if (entity.not_received_messages) handleNewMessage(entity)
32
      if (entity.not_seen_messages) handleNotSeenMessage(entity)
3119 stevensc 33
      if (entity.is_open) handleOpenConversation(entity, false);
687 steven 34
      switch (entity.type) {
35
        case "user":
36
          newUserContacts = [...newUserContacts, entity];
37
          handleUpdateOnline(entity);
38
          break;
39
        case "group":
40
          newGroups = [...newGroups, entity];
41
          break;
42
        default:
43
          break;
44
      }
45
    });
46
    setContacts(newUserContacts);
47
    setGroups(newGroups);
48
  }
2790 stevensc 49
 
687 steven 50
  const heartBeat = async () => {
689 steven 51
    try {
3119 stevensc 52
      const { data } = await axios.get("/chat/heart-beat")
53
      if (data.success) {
54
        handleEntities(data.data)
1 www 55
      }
3119 stevensc 56
      return data.data;
689 steven 57
    } catch (error) {
976 stevensc 58
      console.log('>>: chat error > ', error)
689 steven 59
    }
687 steven 60
  };
1 www 61
 
62
  const handleUpdateOnline = (entity) => {
63
    const existingChatId = activeChats.findIndex(
64
      (activeChat) => activeChat.id === entity.id
65
    );
66
    if (existingChatId >= 0) {
67
      if (activeChats[existingChatId].online !== entity.online) {
68
        const newActiveChats = [...activeChats];
69
        newActiveChats[existingChatId].online = entity.online;
70
        setActiveChats(newActiveChats);
71
      }
72
    }
73
  };
74
 
75
  const handleNewMessage = async (unseeEntity) => {
3596 stevensc 76
    await axios.post(unseeEntity.url_mark_received)
1 www 77
    if (!activeChats.some((activeChat) => activeChat.id === unseeEntity.id)) {
78
      setActiveChats([...activeChats, { ...unseeEntity, minimized: false }]);
79
      playNotifyAudio();
80
    } else {
81
      const existingChatId = activeChats.findIndex(
82
        (activeChat) => activeChat.id === unseeEntity.id
83
      );
84
      if (!activeChats[existingChatId].unsee_messages) {
85
        const newActiveChats = [...activeChats];
86
        newActiveChats[existingChatId].unsee_messages = true;
87
        setActiveChats(newActiveChats);
88
        playNotifyAudio(newActiveChats[existingChatId].minimized);
89
      }
90
    }
91
  };
92
 
3122 stevensc 93
  const handleCloseConversation = async (entity) => {
3127 stevensc 94
    const { data } = await axios.post(entity.url_close)
95
    if (!data.success) console.log('Error in entity close')
96
    setActiveChats(activeChats.filter(prevActiveChats => prevActiveChats.id !== entity.id))
3122 stevensc 97
  }
98
 
99
  const handleOpenConversation = async (entity, minimized = false) => {
3129 stevensc 100
    if (activeChats.length < 3 && !activeChats.some((el) => el.id === entity.id)) {
101
      setActiveChats([...activeChats, { ...entity, minimized: minimized }]);
3127 stevensc 102
    }
3129 stevensc 103
    if (activeChats.length >= 3 && !activeChats.some((el) => el.id === entity.id)) {
104
      await handleCloseConversation(activeChats[0])
105
      setActiveChats(prevActiveChats => [...prevActiveChats, { ...entity, minimized: minimized }]);
986 stevensc 106
    }
1 www 107
  };
108
 
3122 stevensc 109
  const handleReadConversation = async (entity) => {
110
    try {
111
      const { data } = await axios.post(entity.url_mark_seen)
112
      if (!data.success) console.log('Ha ocurrido un error')
113
      setActiveChats(prevActiveChats => [...prevActiveChats].map(chat => {
114
        if (entity.id === chat.id) return { ...chat, not_seen_messages: false }
115
        return chat;
116
      }))
117
    } catch (error) {
118
      console.log(`Error: ${error}`)
1 www 119
    }
120
  };
121
 
3123 stevensc 122
  const handleMinimizeConversation = (entity, minimized = null) => {
123
    return setActiveChats(prevActiveChats => [...prevActiveChats].map(chat => {
3130 stevensc 124
      if (entity.id === chat.id) return { ...chat, minimized: minimized ?? !chat.minimized }
3123 stevensc 125
      return chat
126
    }))
127
  }
1 www 128
 
3119 stevensc 129
  const handleNotSeenMessage = (entity) => {
3111 stevensc 130
    const index = activeChats.findIndex(chat => chat.id === entity.id)
131
 
132
    if (index !== -1) {
133
      setActiveChats(prev => [...prev].map(chat => {
134
        if (chat.id === entity.id) {
135
          return {
136
            ...chat,
137
            not_seen_messages: entity.not_seen_messages
138
          }
139
        }
140
        return chat;
141
      }))
142
    }
3119 stevensc 143
 
144
  }
145
 
1 www 146
  const playNotifyAudio = (minimized = true) => {
147
    if (!isMuted && minimized) {
148
      notifyAudio.play();
149
    }
150
  };
151
 
152
  const handleMute = () => {
153
    setIsMuted(!isMuted);
154
    if (isMuted) {
155
      notifyAudio.play();
156
    }
157
  };
158
 
159
  const handleChangeTab = (tab) => {
160
    setActiveTab(tab);
161
  };
162
 
163
  useEffect(() => {
2548 stevensc 164
    if (!loading) {
2973 stevensc 165
      const fetchData = async () => {
2966 stevensc 166
        setLoading(true)
2973 stevensc 167
        const entities = await heartBeat() || [];
2966 stevensc 168
        setLoading(false)
2973 stevensc 169
 
170
        return entities
2966 stevensc 171
      }
172
 
2989 stevensc 173
      setTimeout(() => {
174
        fetchData()
175
      }, "2000")
691 steven 176
    }
2965 stevensc 177
  }, [loading]);
978 stevensc 178
 
1 www 179
  useEffect(() => {
180
    emojione.imageType = "png";
181
    emojione.sprites = false;
182
    emojione.ascii = true;
183
    emojione.imagePathPNG = props.emojiOnePath;
184
  }, []);
185
 
2069 steven 186
  return (window.innerWidth > 1000 && window.location.pathname !== '/chat') ? (
1 www 187
    <React.Fragment>
188
      <div id="drupalchat-wrapper">
189
        <div id="drupalchat">
190
          <div className="item-list" id="chatbox_chatlist">
191
            <ul id="mainpanel">
192
              <li id="chatpanel" className="first last">
2550 stevensc 193
                <div className="subpanel">
1 www 194
                  <div
195
                    className="subpanel_title"
2554 stevensc 196
                    onClick={(e) => (e.currentTarget === e.target) && setIsChatOpen(!isChatOpen)}
1 www 197
                  >
2554 stevensc 198
                    <a
199
                      href="/chat"
3596 stevensc 200
                      className="text-chat-title"
1 www 201
                    >
2554 stevensc 202
                      Chat
2739 stevensc 203
                      <FiMaximize2 className="ml-3" />
2554 stevensc 204
                    </a>
205
                    <div className="subpanel_title-icons">
2555 stevensc 206
                      <i
207
                        className={`icon ${isMuted ? "icon-volume-off" : "icon-volume-2"} text-20`}
208
                        onClick={handleMute}
209
                      />
210
                      <i
211
                        className={`fa ${isChatOpen ? "fa-angle-down" : "fa-angle-up"} text-20`}
212
                        onClick={() => setIsChatOpen(!isChatOpen)}
213
                      />
1 www 214
                    </div>
215
                  </div>
216
                  <div
217
                    id="showhidechatlist"
2551 stevensc 218
                    style={{ display: isChatOpen ? "grid" : "none" }}
1 www 219
                  >
3595 stevensc 220
                    <div className="drupalchat_search_main chatboxinput">
2561 stevensc 221
                      <input
222
                        className="drupalchat_searchinput live-search-box"
223
                        id="live-search-box"
224
                        type="text"
225
                        name='search'
226
                        value={search}
227
                        onChange={e => setSearch(e.target.value || '')}
228
                      />
229
                      <i className="searchbutton fas fa-search" />
1 www 230
                    </div>
3595 stevensc 231
                    <div className="drupalchat_search_main chatboxinput">
2548 stevensc 232
                      <button
2549 stevensc 233
                        className={`${activeTab === 'user' ? 'active' : ''}`}
2548 stevensc 234
                        onClick={() => handleChangeTab("user")}
1 www 235
                      >
2548 stevensc 236
                        Contactos
237
                      </button>
238
                      <button
2549 stevensc 239
                        className={`${activeTab === 'group' ? 'active' : ''}`}
2548 stevensc 240
                        onClick={() => handleChangeTab("group")}
1 www 241
                      >
2548 stevensc 242
                        Grupos
243
                      </button>
1 www 244
                    </div>
245
                    <div
246
                      className="contact-list chatboxcontent"
3596 stevensc 247
                      style={{ display: activeTab === "user" ? "block" : "none", }}
1 www 248
                    >
249
                      <Contacts
976 stevensc 250
                        contacts={filtredContacts}
1 www 251
                        onOpenConversation={handleOpenConversation}
252
                      />
3058 stevensc 253
                    </div>
1 www 254
                    <div
255
                      className="group-list chatboxcontent"
3596 stevensc 256
                      style={{ display: activeTab === "group" ? "block" : "none", }}
1 www 257
                    >
258
                      <ul id="group-list-ul" className="live-search-list-group">
259
                        <Groups
988 stevensc 260
                          groups={filtredGroups}
1 www 261
                          onOpenConversation={handleOpenConversation}
262
                        />
263
                      </ul>
264
                    </div>
265
                    <div
266
                      className="group-contacts-list chatboxcontent"
267
                      style={{ display: "none" }}
268
                    >
269
                      <div style={{ textAlign: "center", fontSize: "13px" }}>
270
                        Integrantes del grupo
271
                      </div>
272
                      <ul
273
                        id="contact-group-list-ul"
274
                        className="live-search-list"
275
                      ></ul>
276
                    </div>
277
                  </div>
278
                </div>
279
              </li>
280
            </ul>
281
          </div>
282
        </div>
283
      </div>
3133 stevensc 284
      <div className="active_chats-list">
1 www 285
        {activeChats.map((entity, index) => (
286
          <PersonalChat
3131 stevensc 287
            index={index}
1 www 288
            key={entity.id}
289
            entity={entity}
3106 stevensc 290
            not_seen_messages={entity.not_seen_messages}
3131 stevensc 291
            minimized={entity.minimized}
3122 stevensc 292
            onClose={handleCloseConversation}
3123 stevensc 293
            onMinimize={handleMinimizeConversation}
3122 stevensc 294
            onRead={handleReadConversation}
1 www 295
          />
296
        ))}
297
      </div>
1335 stevensc 298
      <NotificationAlert />
1 www 299
    </React.Fragment>
300
  ) : (
301
    ""
302
  );
303
};
304
 
305
export default Chat;