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