Chat.js 6.7 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

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

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

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

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


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

JeongYeonwoo's avatar
JeongYeonwoo committed
187
      </Container >
188
189
      <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
190
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
191
192
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
193
          </Button>
우지원's avatar
ul    
우지원 committed
194
        </Form.Group>
195
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
196
    </>
우지원's avatar
ul    
우지원 committed
197
198
199
200
201


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
202

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