Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7322 | Rev 7324 | 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
    addContacts: (
320
      <>
7322 stevensc 321
        {availableContactsToAdd.length ? (
7323 stevensc 322
          <ul>
323
            {availableContactsToAdd.map(({ image, name, id }) => (
324
              <li key={id}>
325
                <div className="contact-tab">
326
                  <div className="info">
327
                    <Avatar
328
                      src={image}
329
                      alt={`${name} profile image`}
330
                      sx={{
331
                        height: '36px',
332
                        width: '36px',
333
                      }}
334
                    />
335
                    <span>{name}</span>
7322 stevensc 336
                  </div>
7323 stevensc 337
                  <IconButton onClick={() => handleAddPersonToGroup(id)}>
338
                    <Add />
339
                  </IconButton>
340
                </div>
341
              </li>
342
            ))}
343
          </ul>
7322 stevensc 344
        ) : (
7320 stevensc 345
          <EmptySection message={labels.not_contacts} />
7317 stevensc 346
        )}
347
      </>
348
    ),
349
    listContacts: (
350
      <>
7322 stevensc 351
        <SearchInput onChange={(e) => setSearch(e.target.value)} />
7317 stevensc 352
        {filtredGroupList.length ? (
7322 stevensc 353
          <ul>
354
            {filtredGroupList.map(
355
              ({ image, name, url_remove_from_group, id }) => {
356
                return (
357
                  <li key={id}>
358
                    <div className="contact-tab">
359
                      <div className="info">
360
                        <Avatar
361
                          src={image}
362
                          alt={`${name} profile image`}
363
                          sx={{
364
                            height: '36px',
365
                            width: '36px',
366
                          }}
367
                        />
368
                        <span>{name}</span>
369
                      </div>
370
                      {url_remove_from_group && (
371
                        <IconButton
372
                          onClick={() =>
373
                            handleDeletePersonFromGroup(url_remove_from_group)
374
                          }
375
                        >
376
                          <i className="fa fa-user-times" />
377
                        </IconButton>
378
                      )}
379
                    </div>
380
                  </li>
381
                )
382
              }
383
            )}
384
          </ul>
7317 stevensc 385
        ) : (
7322 stevensc 386
          <EmptySection message={labels.not_contacts} />
7317 stevensc 387
        )}
388
      </>
389
    ),
390
  }
391
 
392
  // getMessageOnMaximize and subscribe to infinite Loader
393
  useEffect(async () => {
394
    const options = {
395
      root: null,
396
      rootMargin: '20px',
397
      treshold: 1.0,
398
    }
399
    const observer = new IntersectionObserver(handleObserver, options)
400
    if (!minimized) {
401
      await handleGetMessages()
402
      // loader observer
403
      if (loader.current) {
404
        observer.observe(loader.current)
405
      }
406
    }
407
    return () => {
408
      if (loader.current) {
409
        observer.unobserve(loader.current)
410
      }
411
    }
412
  }, [minimized])
413
 
414
  // LoadMore on change page
415
  useEffect(() => {
416
    let loadMore = () => handleLoadMore()
417
    loadMore()
418
    return () => {
419
      loadMore = null
420
    }
421
  }, [currentPage])
422
 
423
  // getMessagesInterval
424
  useEffect(() => {
425
    if (window.location.pathname === '/group/my-groups') {
426
      const items = document.getElementsByClassName('sc-jSgupP')
427
      if (items && items.length > 0) {
428
        items[0].style.display = 'none'
429
      }
430
    }
431
  }, [minimized])
432
 
433
  useEffect(() => {
434
    let timer
435
    if (!minimized && !loading) {
436
      timer = setTimeout(() => handleGetMessages(), 1000)
437
    }
438
    return () => {
439
      clearTimeout(timer)
440
    }
441
  }, [minimized, loading])
442
 
443
  // useEffect for tabs changing
444
  useEffect(() => {
445
    if (optionTab === 'addContacts') loadPersonsAvailable()
446
    if (optionTab === 'listContacts') loadGroupContacts()
447
  }, [optionTab])
448
 
449
  return (
450
    <>
451
      <div className="personal-chat">
452
        <div className={`chat-header ${not_seen_messages ? 'notify' : ''}`}>
453
          <img src={entity?.image} alt="avatar-image" />
454
          <div className="info-content">
455
            <a href={entity?.profile} target="_blank" rel="noreferrer">
7323 stevensc 456
              {entity?.name}
7317 stevensc 457
            </a>
458
            {entity?.type === 'user' && (
459
              <small className={entity?.online ? 'online' : 'offline'}>
460
                {entity?.online ? 'En línea' : 'Desconectado'}
461
              </small>
462
            )}
463
          </div>
464
          <div className="options ml-auto">
465
            <i
466
              className="cursor-pointer fa fa-gear"
467
              onClick={() =>
468
                showOptions(
469
                  entity?.type === 'user' ? OPTIONS.CONFERENCE : OPTIONS.GROUP
470
                )
471
              }
472
            />
473
            <i
474
              className={'cursor-pointer fa fa-minus-circle'}
475
              onClick={handleActive}
476
            />
477
            <i
478
              className="cursor-pointer fa fa-times-circle"
479
              onClick={handleCloseChat}
480
            />
481
          </div>
482
        </div>
483
 
484
        <div
485
          className="panel-body"
486
          style={{ display: !minimized ? 'block' : 'none' }}
487
        >
488
          {optionTab ? (
489
            <StyledShowOptions>
7323 stevensc 490
              <IconButton
491
                sx={{ marginLeft: '.5rem' }}
492
                onClick={() => showOptions(OPTIONS.INITIAL)}
493
              >
494
                <ArrowBackIos />
495
              </IconButton>
7317 stevensc 496
              <div className="optionsTab">{tabsOptions[optionTab]}</div>
497
            </StyledShowOptions>
498
          ) : (
499
            <>
500
              <ChatList
501
                messages={[...oldMessages, ...messages]}
502
                currentPage={currentPage}
503
                lastPage={lastPage}
504
                conversationList={conversationListEl}
505
                loader={loader}
506
              />
507
              <TextBox
508
                uploadUrl={entity?.url_upload}
509
                isNotSeen={not_seen_messages}
510
                markRead={() => onRead(entity)}
511
                onSend={sendMessage}
512
              />
513
            </>
514
          )}
515
        </div>
516
      </div>
517
      <ConfirmModal
518
        show={confirmModalShow}
519
        onClose={handleConfirmModalShow}
520
        onAccept={handleConfirmModalAccept}
521
      />
522
      <ConferenceModal
523
        show={showConferenceModal}
524
        zoomUrl={entity?.url_zoom}
525
        onClose={() => {
526
          showOptions()
527
          displayConferenceModal()
528
        }}
529
      />
530
    </>
531
  )
532
}
533
 
534
export default React.memo(PersonalChat)