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) => {
76
    await axios.post(unseeEntity.url_mark_received).then((response) => {
976 stevensc 77
      ('')
1 www 78
    });
79
    if (!activeChats.some((activeChat) => activeChat.id === unseeEntity.id)) {
80
      setActiveChats([...activeChats, { ...unseeEntity, minimized: false }]);
81
      playNotifyAudio();
82
    } else {
83
      const existingChatId = activeChats.findIndex(
84
        (activeChat) => activeChat.id === unseeEntity.id
85
      );
86
      if (!activeChats[existingChatId].unsee_messages) {
87
        const newActiveChats = [...activeChats];
88
        newActiveChats[existingChatId].unsee_messages = true;
89
        setActiveChats(newActiveChats);
90
        playNotifyAudio(newActiveChats[existingChatId].minimized);
91
      }
92
    }
93
  };
94
 
3122 stevensc 95
  const handleCloseConversation = async (entity) => {
96
    try {
97
      const { data } = await axios.post(entity.url_close)
98
      if (!data.success) console.log('Error in entity close')
99
      return setActiveChats(activeChats.filter(prevActiveChats => prevActiveChats.id !== entity.id))
100
    } catch (error) {
101
      console.log(error)
1 www 102
    }
3122 stevensc 103
  }
104
 
105
  const handleOpenConversation = async (entity, minimized = false) => {
106
    if (activeChats.some((el) => el.id === entity.id)) return
107
    if (activeChats.length >= 3) {
108
      handleCloseConversation(activeChats[0])
986 stevensc 109
    }
3122 stevensc 110
    try {
111
      const { data } = await axios.post(entity.url_open)
112
      if (!data.success) console.log('Error in open conversation')
113
      return setActiveChats(prevActiveChats => [...prevActiveChats, { ...entity, minimized: minimized }])
114
    } catch (error) {
115
      console.log(error)
116
    }
1 www 117
  };
118
 
3122 stevensc 119
  const handleReadConversation = async (entity) => {
120
    try {
121
      const { data } = await axios.post(entity.url_mark_seen)
122
      if (!data.success) console.log('Ha ocurrido un error')
123
      setActiveChats(prevActiveChats => [...prevActiveChats].map(chat => {
124
        if (entity.id === chat.id) return { ...chat, not_seen_messages: false }
125
        return chat;
126
      }))
127
    } catch (error) {
128
      console.log(`Error: ${error}`)
1 www 129
    }
130
  };
131
 
132
  const handleMinimizeChat = (chatIndex, minimize) => {
133
    const newActiveChats = [...activeChats];
134
    switch (minimize) {
135
      case false:
136
        newActiveChats[chatIndex].minimized = false;
137
        break;
138
      default:
139
        newActiveChats[chatIndex].minimized =
140
          !newActiveChats[chatIndex].minimized;
141
        break;
142
    }
143
    setActiveChats(newActiveChats);
144
  };
145
 
3119 stevensc 146
  const handleNotSeenMessage = (entity) => {
3111 stevensc 147
    const index = activeChats.findIndex(chat => chat.id === entity.id)
148
 
149
    if (index !== -1) {
150
      setActiveChats(prev => [...prev].map(chat => {
151
        if (chat.id === entity.id) {
152
          return {
153
            ...chat,
154
            not_seen_messages: entity.not_seen_messages
155
          }
156
        }
157
        return chat;
158
      }))
159
    }
3119 stevensc 160
 
161
  }
162
 
1 www 163
  const playNotifyAudio = (minimized = true) => {
164
    if (!isMuted && minimized) {
165
      notifyAudio.play();
166
    }
167
  };
168
 
169
  const handleMute = () => {
170
    setIsMuted(!isMuted);
171
    if (isMuted) {
172
      notifyAudio.play();
173
    }
174
  };
175
 
176
  const handleChangeTab = (tab) => {
177
    setActiveTab(tab);
178
  };
179
 
180
  useEffect(() => {
2548 stevensc 181
    if (!loading) {
2973 stevensc 182
      const fetchData = async () => {
2966 stevensc 183
        setLoading(true)
2973 stevensc 184
        const entities = await heartBeat() || [];
2966 stevensc 185
        setLoading(false)
2973 stevensc 186
 
187
        return entities
2966 stevensc 188
      }
189
 
2989 stevensc 190
      setTimeout(() => {
191
        fetchData()
192
      }, "2000")
691 steven 193
    }
2965 stevensc 194
  }, [loading]);
978 stevensc 195
 
1 www 196
  useEffect(() => {
197
    emojione.imageType = "png";
198
    emojione.sprites = false;
199
    emojione.ascii = true;
200
    emojione.imagePathPNG = props.emojiOnePath;
201
  }, []);
202
 
2069 steven 203
  return (window.innerWidth > 1000 && window.location.pathname !== '/chat') ? (
1 www 204
    <React.Fragment>
205
      <div id="drupalchat-wrapper">
206
        <div id="drupalchat">
207
          <div className="item-list" id="chatbox_chatlist">
208
            <ul id="mainpanel">
209
              <li id="chatpanel" className="first last">
2550 stevensc 210
                <div className="subpanel">
1 www 211
                  <div
212
                    className="subpanel_title"
2554 stevensc 213
                    onClick={(e) => (e.currentTarget === e.target) && setIsChatOpen(!isChatOpen)}
1 www 214
                  >
2554 stevensc 215
                    <a
216
                      href="/chat"
217
                      className="text-gray text-chat-title"
1 www 218
                    >
2554 stevensc 219
                      Chat
2739 stevensc 220
                      <FiMaximize2 className="ml-3" />
2554 stevensc 221
                    </a>
222
                    <div className="subpanel_title-icons">
2555 stevensc 223
                      <i
224
                        className={`icon ${isMuted ? "icon-volume-off" : "icon-volume-2"} text-20`}
225
                        onClick={handleMute}
226
                      />
227
                      <i
228
                        className={`fa ${isChatOpen ? "fa-angle-down" : "fa-angle-up"} text-20`}
229
                        onClick={() => setIsChatOpen(!isChatOpen)}
230
                      />
1 www 231
                    </div>
232
                  </div>
233
                  <div
234
                    id="showhidechatlist"
2551 stevensc 235
                    style={{ display: isChatOpen ? "grid" : "none" }}
1 www 236
                  >
237
                    <div
238
                      className="drupalchat_search_main chatboxinput"
239
                      style={{ background: "#f9f9f9" }}
240
                    >
2561 stevensc 241
                      <input
242
                        className="drupalchat_searchinput live-search-box"
243
                        id="live-search-box"
244
                        type="text"
245
                        name='search'
246
                        value={search}
247
                        onChange={e => setSearch(e.target.value || '')}
248
                      />
249
                      <i className="searchbutton fas fa-search" />
1 www 250
                    </div>
251
                    <div
252
                      className="drupalchat_search_main chatboxinput"
253
                      style={{ background: "#f9f9f9" }}
254
                    >
2548 stevensc 255
                      <button
2549 stevensc 256
                        className={`${activeTab === 'user' ? 'active' : ''}`}
2548 stevensc 257
                        onClick={() => handleChangeTab("user")}
1 www 258
                      >
2548 stevensc 259
                        Contactos
260
                      </button>
261
                      <button
2549 stevensc 262
                        className={`${activeTab === 'group' ? 'active' : ''}`}
2548 stevensc 263
                        onClick={() => handleChangeTab("group")}
1 www 264
                      >
2548 stevensc 265
                        Grupos
266
                      </button>
1 www 267
                    </div>
268
                    <div
269
                      className="contact-list chatboxcontent"
270
                      style={{
271
                        display: activeTab === "user" ? "block" : "none",
272
                      }}
273
                    >
274
                      <Contacts
976 stevensc 275
                        contacts={filtredContacts}
1 www 276
                        onOpenConversation={handleOpenConversation}
277
                      />
3058 stevensc 278
                    </div>
1 www 279
                    <div
280
                      className="group-list chatboxcontent"
281
                      style={{
282
                        display: activeTab === "group" ? "block" : "none",
283
                      }}
284
                    >
285
                      <ul id="group-list-ul" className="live-search-list-group">
286
                        <Groups
988 stevensc 287
                          groups={filtredGroups}
1 www 288
                          onOpenConversation={handleOpenConversation}
289
                        />
290
                      </ul>
291
                    </div>
292
                    <div
293
                      className="group-contacts-list chatboxcontent"
294
                      style={{ display: "none" }}
295
                    >
296
                      <div style={{ textAlign: "center", fontSize: "13px" }}>
297
                        Integrantes del grupo
298
                      </div>
299
                      <ul
300
                        id="contact-group-list-ul"
301
                        className="live-search-list"
302
                      ></ul>
303
                    </div>
304
                  </div>
305
                </div>
306
              </li>
307
            </ul>
308
          </div>
309
        </div>
310
      </div>
311
      <div style={{ display: "flex" }}>
312
        {activeChats.map((entity, index) => (
313
          <PersonalChat
314
            key={entity.id}
315
            entity={entity}
3106 stevensc 316
            not_seen_messages={entity.not_seen_messages}
1 www 317
            index={index}
3122 stevensc 318
            onClose={handleCloseConversation}
1 www 319
            onMinimize={handleMinimizeChat}
3122 stevensc 320
            onRead={handleReadConversation}
3120 stevensc 321
            loading={loading}
1 www 322
          />
323
        ))}
324
      </div>
1335 stevensc 325
      <NotificationAlert />
1 www 326
    </React.Fragment>
327
  ) : (
328
    ""
329
  );
330
};
331
 
332
export default Chat;