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