Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

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