Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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