Chat.js 6.68 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: ''
}
우지원's avatar
ul    
우지원 committed
14
function Chat(props) {
Choi Ga Young's avatar
Choi Ga Young committed
15
  //const [sender, setSender] = useState([])
JeongYeonwoo's avatar
JeongYeonwoo committed
16

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

21
22
23
24
  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
25
26
27
28
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

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

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

Choi Ga Young's avatar
Choi Ga Young committed
33
34
35
36
37
38
39
40
  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
41

42
43
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
44
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
45
    setDisabled(false)
Choi Ga Young's avatar
Choi Ga Young committed
46
    //console.log(chat)
47
48
49
  }

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

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

Choi Ga Young's avatar
Choi Ga Young committed
61
  function handleClick() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
62
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
63
    props.setRecievedMsg('')
Choi Ga Young's avatar
Choi Ga Young committed
64
    props.handleChatc()
65
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
66
    console.log('나간시간', realTime, usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
67
68
    setChat([''])

69
    props.handleChatc()
70
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  }

  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 } })
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
91
    console.log(respond)
92
    const info = respond.data
JeongYeonwoo's avatar
JeongYeonwoo committed
93
94
95
96
97

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

Choi Ga Young's avatar
Choi Ga Young committed
103
  async function exitAndCloseRoom() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
104
105
106
107
    props.exitRoom(props.roomCode)
    setExit(false)
    props.handleChatc()
  }
Choi Ga Young's avatar
Choi Ga Young committed
108

Soo Hyun Kim's avatar
Soo Hyun Kim committed
109

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
110
111
112
  useEffect(() => {
    getProfile(userId)
  }, [userId])
113

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

Soo Hyun Kim's avatar
Soo Hyun Kim committed
118
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
119
    setChat([...chat, { msg: props.recievedMsg, sender: props.recievedUser, img: props.recievedImg, time: props.recievedTime }])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
120
121
  }, [props.recievedMsg])

122
123
  useEffect(() => {
    getPreviousChat()
JeongYeonwoo's avatar
JeongYeonwoo committed
124
    // console.log('겟 룸네임', chat)
125
126
127
  }, [props.roomCode])


우지원's avatar
ul    
우지원 committed
128
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
129
130
    <>
      <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
131
        <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
132
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
133
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
134
135
          </Col>
          <Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
136
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
137
138
            <Row > {props.roomCode} </Row>
          </Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
139
140
          <Col md="auto">
            <Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
141
142
          </Col>
        </Row>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
143
144
145
146
147
148
        {exit ?
          <Row>
            <Col>퇴장하시겠습니까?</Col>
            <Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
          </Row>
          : null}
JeongYeonwoo's avatar
JeongYeonwoo committed
149
        {chat.map((value, index) => {
150
          if (!(value.msg === '')) {
Choi Ga Young's avatar
Choi Ga Young committed
151
152
153
154
155
156
157
            if (value.sender === "system") {
              return (
                <Row className='border' style={{ background: "#FFFAFA"}}>
                  {value.msg}
                </Row>
              )
            } else if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
158
159
160
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
JeongYeonwoo's avatar
JeongYeonwoo committed
161
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
162
163
                  </Col>
                  <Col xs={8}>
JeongYeonwoo's avatar
JeongYeonwoo committed
164
                    <Row><strong>{value.sender}</strong></Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
165
                    <Row className='d-flex flex-wrap-nowrap'>
JeongYeonwoo's avatar
JeongYeonwoo committed
166
167
                      <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
168
169
                    </Row>
                  </Col>
170
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
171
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
172
173
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
174
175
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
176
177
                    <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
178
                  </Row>
179
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
180
181
182
183
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
184
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
185
        })
186
        }
Choi Ga Young's avatar
Choi Ga Young committed
187

JeongYeonwoo's avatar
JeongYeonwoo committed
188
      </Container >
189
190
      <Form onSubmit={sendMsgCH} fluid>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
Choi Ga Young's avatar
Choi Ga Young committed
191
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
192
193
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
194
          </Button>
우지원's avatar
ul    
우지원 committed
195
        </Form.Group>
196
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
197
    </>
우지원's avatar
ul    
우지원 committed
198
199
200
201
202


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
203

우지원's avatar
ul    
우지원 committed
204
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
205