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