Chat.js 6.84 KB
Newer Older
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
1
import axios from 'axios';
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
2
import React, { useState, useEffect } from 'react';
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
3
4
5
import { Form, Button, Row, Image, Col, Container } from 'react-bootstrap';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
우지원's avatar
ul    
우지원 committed
6

JeongYeonwoo's avatar
JeongYeonwoo committed
7
8
9
10
11
12
13

const INIT_CHAT = {
  msg: '',
  sender: '',
  img: '',
  time: ''
}
14

우지원's avatar
ul    
우지원 committed
15
function Chat(props) {
JeongYeonwoo's avatar
JeongYeonwoo committed
16
17
  const [sender, setSender] = useState([])

Choi Ga Young's avatar
Choi Ga Young committed
18
  //const [roomName, setRoomName] = useState('')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
19
  const [inner, setInner] = useState([''])
JeongYeonwoo's avatar
JeongYeonwoo committed
20
  const [chat, setChat] = useState([INIT_CHAT])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
JeongYeonwoo committed
21

22
23
24
25
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()

Choi Ga Young's avatar
Choi Ga Young committed
26
27
28
29
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

Soo Hyun Kim's avatar
Soo Hyun Kim committed
30
  const [exit, setExit] = useState(false);
Choi Ga Young's avatar
Choi Ga Young committed
31
32

  const userId = isAuthenticated()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
33

Choi Ga Young's avatar
Choi Ga Young committed
34
35
36
37
38
39
40
41
  async function getProfile(userId) {
    try {
      const response = await axios.get(`/users/${userId}`)
      setUser(response.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
42

43
44
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
45
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
46
    setDisabled(false)
47
48

    console.log(props.leftInfo)
49
50
51
  }

  function sendMsgCH(e) {
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
52
    e.preventDefault()
JeongYeonwoo's avatar
JeongYeonwoo committed
53

54
    props.setSingleTime(usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
55
56
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
57
    props.setSingleChat(inner)
58
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
59
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
60
    setDisabled(true)
61
62

    recordEntryLog()  //그냥 새로고침해도 최신화
63
  }
Choi Ga Young's avatar
Choi Ga Young committed
64

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

  async function recordEntryLog() {
    const leaveInfo = { userId: userId, roomCode: props.roomCode, leaveTime: realTime }
    try {
      const check = await axios.get('/room/entrylog', { params: leaveInfo })
      if (check.data) {       //있으면 put으로
        await axios.put('/room/entrylog', leaveInfo)
      } else {        //없으면 post
        await axios.post('/room/entrylog', leaveInfo)
      }
    } catch (error) {
      catchErrors(error, setError)
    }

  }


Choi Ga Young's avatar
Choi Ga Young committed
82
  function handleClick() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
83
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
84
    props.setRecievedMsg('')
Choi Ga Young's avatar
Choi Ga Young committed
85
    props.handleChatc()
JeongYeonwoo's avatar
JeongYeonwoo committed
86
87
    setChat([''])

88
    recordEntryLog()
89
    props.setRoomCode('')
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
  }

  function settingtime(hour) {
    let newhour = parseInt(hour) + 9
    if (newhour >= 24) {
      newhour -= 24
    }
    if (newhour >= 13) {
      newhour -= 12
      newhour = '오후 ' + newhour
    } else {
      newhour = '오전 ' + newhour
    }
    return newhour
  }

  //이전 채팅 내용에 대한 것 불러오기
  //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
  async function getPreviousChat() {
    const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
    const info = respond.data
JeongYeonwoo's avatar
JeongYeonwoo committed
111
112
113
114
115

    let intochat = []
    for (let prop in info) {
      let hour = info[prop].createdAt.split('T')[1].split(':')
      hour = settingtime(hour[0]) + ':' + hour[1]
116
      intochat.push({ msg: info[prop].message, sender: info[prop].username, img: info[prop].profileimg, time: hour })
117
    }
JeongYeonwoo's avatar
JeongYeonwoo committed
118
    setChat(intochat)
Choi Ga Young's avatar
Choi Ga Young committed
119
120
  }

Choi Ga Young's avatar
Choi Ga Young committed
121
  async function exitAndCloseRoom() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
122
123
124
125
    props.exitRoom(props.roomCode)
    setExit(false)
    props.handleChatc()
  }
Choi Ga Young's avatar
Choi Ga Young committed
126

Soo Hyun Kim's avatar
Soo Hyun Kim committed
127

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
128
129
130
  useEffect(() => {
    getProfile(userId)
  }, [userId])
131

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
132
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
133
    setChat([...chat, { msg: props.singleChat, sender: props.singleUser, img: props.singleImg, time: props.singleTime }])
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
134
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
135

Soo Hyun Kim's avatar
Soo Hyun Kim committed
136
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
137
    setChat([...chat, { msg: props.recievedMsg, sender: props.recievedUser, img: props.recievedImg, time: props.recievedTime }])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
138
139
  }, [props.recievedMsg])

140
141
142
143
144
  useEffect(() => {
    getPreviousChat()
  }, [props.roomCode])


우지원's avatar
ul    
우지원 committed
145
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
146
147
    <>
      <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
148
        <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
149
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
150
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
151
152
          </Col>
          <Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
153
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
154
155
            <Row > {props.roomCode} </Row>
          </Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
156
157
          <Col md="auto">
            <Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
158
159
          </Col>
        </Row>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
160
161
162
163
164
165
        {exit ?
          <Row>
            <Col>퇴장하시겠습니까?</Col>
            <Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
          </Row>
          : null}
JeongYeonwoo's avatar
JeongYeonwoo committed
166
        {chat.map((value, index) => {
167
          if (!(value.msg === '')) {
JeongYeonwoo's avatar
JeongYeonwoo committed
168
            if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
169
170
171
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
JeongYeonwoo's avatar
JeongYeonwoo committed
172
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
173
174
                  </Col>
                  <Col xs={8}>
JeongYeonwoo's avatar
JeongYeonwoo committed
175
                    <Row><strong>{value.sender}</strong></Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
176
                    <Row className='d-flex flex-wrap-nowrap'>
JeongYeonwoo's avatar
JeongYeonwoo committed
177
178
                      <Row className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Row>
                      <Col className='ml-1'>{value.time}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
179
180
                    </Row>
                  </Col>
181
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
182
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
183
            } else if (sender[index] === "") {
JeongYeonwoo's avatar
JeongYeonwoo committed
184
              return (
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
185
186
187
188
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
189
190
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
191
192
                    <Col className='mr-1'>{value.time}</Col>
                    <Row className='mr-2' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value.msg}</Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
193
                  </Row>
194
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
195
196
197
198
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
199
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
200
        })
201
        }
Choi Ga Young's avatar
Choi Ga Young committed
202

JeongYeonwoo's avatar
JeongYeonwoo committed
203
      </Container >
204
205
      <Form onSubmit={sendMsgCH} fluid>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
206
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
207
208
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
209
          </Button>
우지원's avatar
ul    
우지원 committed
210
        </Form.Group>
211
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
212
    </>
우지원's avatar
ul    
우지원 committed
213
214
215
216
217


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
218

우지원's avatar
ul    
우지원 committed
219
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
220