Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7320 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
7317 stevensc 1
import React, { useEffect, useRef, useState } from 'react'
2
import { axios } from '../../../utils'
3
import { useSelector } from 'react-redux'
4
import styled from 'styled-components'
5
import SearchIcon from '@mui/icons-material/Search'
6
 
7
import TextBox from './TextBox'
8
import ChatList from './ChatList'
9
import EmptySection from '../../UI/EmptySection'
10
import ConfirmModal from '../../modals/ConfirmModal'
11
import ConferenceModal from '../../modals/ConferenceModal'
12
 
13
const StyledShowOptions = styled.div`
14
  height: 342px;
15
  flex-direction: column;
16
  gap: 0.5rem;
17
  overflow-y: auto;
18
  position: relative;
19
  &.show {
20
    display: flex;
21
  }
22
  &.hide {
23
    display: none;
24
  }
25
  .optionBack {
26
    margin: 1rem 0 0.5rem 1rem;
27
    cursor: pointer;
28
  }
29
  .optionsTab {
30
    &__option {
31
      padding: 0.5rem;
32
      border-bottom: 1px solid #e2e2e2;
33
      cursor: pointer;
34
      &:hover {
35
        background-color: #e2e2e2;
36
      }
37
      &__icon {
38
        margin-right: 0.3rem;
39
      }
40
    }
41
  }
42
  .addPersonToGroupTab {
43
    display: flex;
44
    flex-direction: column;
45
    &__person {
46
      display: flex;
47
      justify-content: space-between;
48
      align-items: center;
49
      padding: 0.2rem 0.5rem;
50
      border-bottom: 1px solid #e2e2e2;
51
    }
52
  }
53
`
54
 
55
const OPTIONS = {
56
  GROUP: 'group',
57
  CONFERENCE: 'conference',
58
  ADD_CONTACTS: 'addContacts',
59
  LIST_CONTACTS: 'listContacts',
60
  INITIAL: null,
61
}
62
 
63
const PersonalChat = ({
64
  entity,
65
  onClose,
66
  onMinimize,
67
  onRead,
68
  not_seen_messages,
69
  minimized,
70
}) => {
71
  const [optionTab, setOptionTab] = useState(OPTIONS.INITIAL)
72
  const [availableContactsToAdd, setAvailableContactsToAdd] = useState([])
73
  const [groupContactsList, setGroupContactsList] = useState([])
74
  const [confirmModalShow, setConfirmModalShow] = useState(false)
75
  const [showConferenceModal, setShowConferenceModal] = useState(false)
76
  const [search, setSearch] = useState('')
77
  const [messages, setMessages] = useState([])
78
  const [oldMessages, setOldMessages] = useState([])
79
  const [currentPage, setCurrentPage] = useState(1)
80
  const [lastPage, setLastPage] = useState(1)
81
  const [loading, setLoading] = useState(false)
82
  const labels = useSelector(({ intl }) => intl.labels)
83
 
84
  const filtredGroupList = groupContactsList.filter((conversation) =>
85
    conversation.name.toLowerCase().includes(search.toLowerCase())
86
  )
87
 
88
  // refs
89
  const conversationListEl = useRef(null)
90
  const loader = useRef(null)
91
  const modalActionUrl = useRef('')
92
 
93
  const handleActive = () => {
94
    onRead(entity)
95
    onMinimize(entity)
96
  }
97
 
98
  const handleGetMessages = async () => {
99
    setLoading(true)
100
    const response = await axios.get(entity?.url_get_all_messages)
101
    const resData = response.data
102
    if (!resData.success) {
103
      return 'ha ocurrido un error'
104
    }
105
    const updatedMessages = [...resData.data.items].reverse()
106
    const newMessages = updatedMessages.reduce((acum, updatedMessage) => {
107
      if (
108
        messages.findIndex((message) => message.id === updatedMessage.id) === -1
109
      ) {
110
        acum = [...acum, updatedMessage]
111
      }
112
      return acum
113
    }, [])
114
 
115
    if (newMessages.length > 0) {
116
      setMessages([...messages, ...newMessages])
117
      setLoading(false)
118
      setLastPage(resData.data.pages)
119
      scrollToBottom()
120
    } else {
121
      setLoading(false)
122
    }
123
  }
124
 
125
  const handleLoadMore = async () => {
126
    await axios
127
      .get(`${entity?.url_get_all_messages}?page=${currentPage}`)
128
      .then((response) => {
129
        const resData = response.data
130
        if (resData.success) {
131
          if (resData.data.page > 1) {
132
            const updatedOldMessages = [...resData.data.items].reverse()
133
            setOldMessages([...updatedOldMessages, ...oldMessages])
134
            /* scrollDownBy(100); */
135
          }
136
        }
137
      })
138
  }
139
 
140
  const handleCloseChat = () => onClose(entity)
141
 
142
  const sendMessage = async (message) => {
143
    const formData = new FormData()
144
    formData.append('message', emojione.toShort(message))
145
    await axios.post(entity?.url_send, formData).then((response) => {
146
      const resData = response.data
147
      if (resData.success) {
148
        let newMessage = resData.data
149
 
150
        entity?.online
151
          ? (newMessage = { ...newMessage, not_received: false })
152
          : (newMessage = { ...newMessage, not_received: true })
153
 
154
        setMessages([...messages, newMessage])
155
      }
156
    })
157
    // await handleGetMessages()
158
    // setResponseMessage(null)
159
  }
160
 
161
  const showOptions = (tab = OPTIONS.INITIAL) => {
162
    onMinimize(entity, false)
163
    setOptionTab(tab)
164
  }
165
 
166
  const handleAddPersonToGroup = async (id) => {
167
    const formData = new FormData()
168
    formData.append('uid', id)
169
    await axios
170
      .post(entity?.url_add_user_to_group, formData)
171
      .then((response) => {
172
        const resData = response.data
173
        if (resData.success) {
174
          loadPersonsAvailable()
175
        }
176
      })
177
  }
178
 
179
  const handleConfirmModalAction = async () => {
180
    try {
181
      const { data } = await axios.post(modalActionUrl.current)
182
      if (!data.success) console.log('Error in confirm modal action')
183
      handleConfirmModalShow()
184
      onClose(entity)
185
      return
186
    } catch (error) {
187
      console.log(error)
188
    }
189
  }
190
 
191
  const handleObserver = (entities) => {
192
    const target = entities[0]
193
    if (target.isIntersecting) {
194
      setCurrentPage((prevState) => prevState + 1)
195
    }
196
  }
197
 
198
  const scrollToBottom = () => {
199
    if (conversationListEl.current) {
200
      conversationListEl.current.scrollTop =
201
        conversationListEl.current.scrollHeight * 9
202
    }
203
  }
204
 
205
  const handleConfirmModalShow = () => setConfirmModalShow(!confirmModalShow)
206
 
207
  const handleConfirmModalAccept = () => handleConfirmModalAction()
208
 
209
  /* const handleResponseMessage = (element) => {
210
    element.mtype === 'text'
211
      ? setResponseMessage(element)
212
      : setResponseMessage({ ...element, m: 'Archivo adjunto' })
213
 
214
    textAreaEl.current && textAreaEl.current.focus()
215
  } */
216
 
217
  const displayConferenceModal = () =>
218
    setShowConferenceModal(!showConferenceModal)
219
 
220
  const loadPersonsAvailable = async () => {
221
    await axios
222
      .get(entity?.url_get_contacts_availables_for_group)
223
      .then((response) => {
224
        const resData = response.data
225
        if (resData.success) {
226
          setAvailableContactsToAdd(resData.data)
227
        }
228
      })
229
  }
230
 
231
  const loadGroupContacts = async () => {
232
    await axios.get(entity?.url_get_contact_group_list).then((response) => {
233
      const resData = response.data
234
      if (resData.success) {
235
        setGroupContactsList(resData.data)
236
      }
237
    })
238
  }
239
 
240
  const handleDeletePersonFromGroup = async (urlDeletePersonFromGroup) => {
241
    await axios.post(urlDeletePersonFromGroup).then((response) => {
242
      const resData = response.data
243
      if (resData.success) {
244
        loadGroupContacts()
245
      }
246
    })
247
  }
248
 
249
  const tabsOptions = {
250
    group: (
251
      <ul>
252
        {entity?.url_get_contact_group_list && (
253
          <li
254
            className="optionsTab__option"
255
            onClick={() => showOptions(OPTIONS.LIST_CONTACTS)}
256
          >
257
            <span className="optionsTab__option__icon">
258
              <i className="fa fa-group" />
259
              Integrantes
260
            </span>
261
          </li>
262
        )}
263
        {entity?.url_add_user_to_group && (
264
          <li
265
            className="optionsTab__option"
266
            onClick={() => showOptions(OPTIONS.ADD_CONTACTS)}
267
          >
268
            <span className="optionsTab__option__icon">
269
              <i className="fa fa-user-plus"></i>
270
            </span>
271
            {labels.ADD_CONTACTS}
272
          </li>
273
        )}
274
        {entity?.url_zoom && (
275
          <li className="optionsTab__option" onClick={displayConferenceModal}>
276
            <span className="optionsTab__option__icon">
277
              <i className="fa fa-user-plus" />
278
            </span>
279
            {labels.CREATE_CONFERENCE}
280
          </li>
281
        )}
282
        {entity?.url_delete && (
283
          <li
284
            className="optionsTab__option"
285
            style={{ color: 'red' }}
286
            onClick={() => {
287
              handleConfirmModalShow()
288
              modalActionUrl.current = entity?.url_delete
289
            }}
290
          >
291
            <span className="optionsTab__option__icon">
292
              <i className="fa fa-trash"></i>
293
            </span>
294
            Eliminar grupo
295
          </li>
296
        )}
297
        {!!entity?.url_leave && (
298
          <li
299
            className="optionsTab__option"
300
            style={{ color: 'red' }}
301
            onClick={() => {
302
              handleConfirmModalShow()
303
              modalActionUrl.current = entity?.url_leave
304
            }}
305
          >
306
            <span className="optionsTab__option__icon">
307
              <i className="fa fa-user-times"></i>
308
            </span>
309
            Dejar grupo
310
          </li>
311
        )}
312
      </ul>
313
    ),
314
    conference: (
315
      <ul>
316
        <li className="optionsTab__option" onClick={displayConferenceModal}>
317
          <span className="optionsTab__option__icon">
318
            <i className="fa fa-user-plus" />
319
          </span>
320
          {labels.CREATE_CONFERENCE}
321
        </li>
322
      </ul>
323
    ),
324
    addContacts: (
325
      <>
326
        {!availableContactsToAdd.length ? (
327
          <EmptySection message={labels.NOT_CONTACTS} align="left" />
328
        ) : (
329
          availableContactsToAdd.map(({ image, name, id }) => (
330
            <div className="addPersonToGroupTab__person" key={id}>
331
              <div className="d-inline-flex" style={{ gap: '5px' }}>
332
                <img
333
                  className="chat-image img-circle pull-left"
334
                  height="36"
335
                  width="36"
336
                  src={image}
337
                  alt="image-image"
338
                />
339
                <div className="name">{name}</div>
340
              </div>
341
              <span
342
                className="cursor-pointer"
343
                onClick={() => handleAddPersonToGroup(id)}
344
              >
345
                <i className="fa fa-plus-circle" />
346
              </span>
347
            </div>
348
          ))
349
        )}
350
      </>
351
    ),
352
    listContacts: (
353
      <>
354
        <div className="group__search">
355
          <SearchIcon />
356
          <input
357
            type="text"
358
            placeholder={labels.SEARCH}
359
            onChange={(e) => setSearch(e.target.value)}
360
          />
361
        </div>
362
        {filtredGroupList.length ? (
363
          filtredGroupList.map(({ image, name, url_remove_from_group, id }) => {
364
            return (
365
              <div className="addPersonToGroupTab__person" key={id}>
366
                <div style={{ display: 'flex', alignItems: 'center' }}>
367
                  <img
368
                    className="chat-image img-circle pull-left"
369
                    height="36"
370
                    width="36"
371
                    src={image}
372
                    alt="image-image"
373
                  />
374
                  <div className="name">{name}</div>
375
                </div>
376
                {url_remove_from_group && (
377
                  <span
378
                    className="cursor-pointer"
379
                    onClick={() =>
380
                      handleDeletePersonFromGroup(url_remove_from_group)
381
                    }
382
                  >
383
                    <i className="fa fa-user-times" />
384
                  </span>
385
                )}
386
              </div>
387
            )
388
          })
389
        ) : (
390
          <div className="addPersonToGroupTab__person">
391
            {labels.NOT_CONTACTS}
392
          </div>
393
        )}
394
      </>
395
    ),
396
  }
397
 
398
  // getMessageOnMaximize and subscribe to infinite Loader
399
  useEffect(async () => {
400
    const options = {
401
      root: null,
402
      rootMargin: '20px',
403
      treshold: 1.0,
404
    }
405
    const observer = new IntersectionObserver(handleObserver, options)
406
    if (!minimized) {
407
      await handleGetMessages()
408
      // loader observer
409
      if (loader.current) {
410
        observer.observe(loader.current)
411
      }
412
    }
413
    return () => {
414
      if (loader.current) {
415
        observer.unobserve(loader.current)
416
      }
417
    }
418
  }, [minimized])
419
 
420
  // LoadMore on change page
421
  useEffect(() => {
422
    let loadMore = () => handleLoadMore()
423
    loadMore()
424
    return () => {
425
      loadMore = null
426
    }
427
  }, [currentPage])
428
 
429
  // getMessagesInterval
430
  useEffect(() => {
431
    if (window.location.pathname === '/group/my-groups') {
432
      const items = document.getElementsByClassName('sc-jSgupP')
433
      if (items && items.length > 0) {
434
        items[0].style.display = 'none'
435
      }
436
    }
437
  }, [minimized])
438
 
439
  useEffect(() => {
440
    let timer
441
    if (!minimized && !loading) {
442
      timer = setTimeout(() => handleGetMessages(), 1000)
443
    }
444
    return () => {
445
      clearTimeout(timer)
446
    }
447
  }, [minimized, loading])
448
 
449
  // useEffect for tabs changing
450
  useEffect(() => {
451
    if (optionTab === 'addContacts') loadPersonsAvailable()
452
    if (optionTab === 'listContacts') loadGroupContacts()
453
  }, [optionTab])
454
 
455
  return (
456
    <>
457
      <div className="personal-chat">
458
        <div className={`chat-header ${not_seen_messages ? 'notify' : ''}`}>
459
          <img src={entity?.image} alt="avatar-image" />
460
          <div className="info-content">
461
            <a href={entity?.profile} target="_blank" rel="noreferrer">
462
              {name}
463
            </a>
464
            {entity?.type === 'user' && (
465
              <small className={entity?.online ? 'online' : 'offline'}>
466
                {entity?.online ? 'En línea' : 'Desconectado'}
467
              </small>
468
            )}
469
          </div>
470
          <div className="options ml-auto">
471
            <i
472
              className="cursor-pointer fa fa-gear"
473
              onClick={() =>
474
                showOptions(
475
                  entity?.type === 'user' ? OPTIONS.CONFERENCE : OPTIONS.GROUP
476
                )
477
              }
478
            />
479
            <i
480
              className={'cursor-pointer fa fa-minus-circle'}
481
              onClick={handleActive}
482
            />
483
            <i
484
              className="cursor-pointer fa fa-times-circle"
485
              onClick={handleCloseChat}
486
            />
487
          </div>
488
        </div>
489
 
490
        <div
491
          className="panel-body"
492
          style={{ display: !minimized ? 'block' : 'none' }}
493
        >
494
          {optionTab ? (
495
            <StyledShowOptions>
496
              <span className="optionBack" onClick={() => showOptions()}>
497
                <i className="fa icon-arrow-left" />
498
              </span>
499
              <div className="optionsTab">{tabsOptions[optionTab]}</div>
500
            </StyledShowOptions>
501
          ) : (
502
            <>
503
              <ChatList
504
                messages={[...oldMessages, ...messages]}
505
                currentPage={currentPage}
506
                lastPage={lastPage}
507
                conversationList={conversationListEl}
508
                loader={loader}
509
              />
510
              <TextBox
511
                uploadUrl={entity?.url_upload}
512
                isNotSeen={not_seen_messages}
513
                markRead={() => onRead(entity)}
514
                onSend={sendMessage}
515
              />
516
            </>
517
          )}
518
        </div>
519
      </div>
520
      <ConfirmModal
521
        show={confirmModalShow}
522
        onClose={handleConfirmModalShow}
523
        onAccept={handleConfirmModalAccept}
524
      />
525
      <ConferenceModal
526
        show={showConferenceModal}
527
        zoomUrl={entity?.url_zoom}
528
        onClose={() => {
529
          showOptions()
530
          displayConferenceModal()
531
        }}
532
      />
533
    </>
534
  )
535
}
536
 
537
export default React.memo(PersonalChat)