Chat.js 8.13 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';
Soo Hyun Kim's avatar
Soo Hyun Kim committed
6
7
import { BsCaretLeftFill, BsList, BsExclamationCircleFill, BsCheck, BsX } from "react-icons/bs";
import { FiSend } from "react-icons/fi";
JeongYeonwoo's avatar
JeongYeonwoo committed
8

JeongYeonwoo's avatar
JeongYeonwoo committed
9
10
11
12
13
14
const INIT_CHAT = {
  msg: '',
  sender: '',
  img: '',
  time: ''
}
우지원's avatar
ul    
우지원 committed
15
function Chat(props) {
Choi Ga Young's avatar
Choi Ga Young committed
16
  //const [sender, setSender] = useState([])
JeongYeonwoo's avatar
JeongYeonwoo committed
17

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
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()
JeongYeonwoo's avatar
JeongYeonwoo committed
25

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)
Choi Ga Young's avatar
Choi Ga Young committed
47
    //console.log(chat)
48
49
50
  }

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

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

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

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

  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
Choi Ga Young's avatar
Choi Ga Young committed
86
87
  }

88
89
90
91
  //이전 채팅 내용에 대한 것 불러오기
  //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
  async function getPreviousChat() {
    const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
92
    console.log(respond)
93
    const info = respond.data
JeongYeonwoo's avatar
JeongYeonwoo committed
94
95
96
97
98

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

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

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 (
Soo Hyun Kim's avatar
Soo Hyun Kim committed
129
130
    <div id="chat" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', width: "100%", height: "580px", position: "relative" }}>
      <div id="chat-head" style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center", width: "100%", height: "80px" }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
131
        <a  href="#;" onClick={handleClick} style={{ margin: "0px 0px 0px 15px" }}><BsCaretLeftFill size="20" color="#333333" /></a>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
132
        <div style={{ justifyContent: "center" }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
133
134
          <p style={{ color: "#333333", fontWeight: "bold", fontSize: "1.6em", textAlign: "center", margin: "0px 0px 0.5px 0px" }}> {props.roomName} </p>
          <p style={{ color: "#333333", fontSize: "0.8em", textAlign: "center", margin: "0.5px 0px 0px 0px" }}> {props.roomCode} </p>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
135
        </div>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
136
        <a href="#;" onClick={() => setExit(!exit)} style={{ margin: "0px 15px 0px 0px" }}><BsList size="20" color="#333333" /></a>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
137
138
139
140
      </div>
      {exit ?
        <div id="chat-exit-check" style={{ display: "flex", flexDirection: "row", justifyContent: "space-evenly", alignItems: "center", margin: "1%", backgroundColor: "#30284D", borderRadius: "5px", height: "50px" }}>
          <p style={{ width: "70%", color: "#FAFAFA", fontSize: "1em", margin: "0px 10px 0px 20px" }}><BsExclamationCircleFill size="1em" color="#F2D788" />  퇴장하시겠습니까?</p>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
141
142
          <a href="#;" onClick={exitAndCloseRoom}><BsCheck size="1em" color="#F2D788" /></a>
          <a href="#;" onClick={() => setExit(!exit)}><BsX size="1em" color="#F2D788" /></a>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
143
144
        </div>
        : null}
Soo Hyun Kim's avatar
Soo Hyun Kim committed
145
      <div id="chat-body" style={{ overflow: 'auto', padding: '15px', width: "100%", height: "400px", margin: "1%", background: '' }}>
JeongYeonwoo's avatar
JeongYeonwoo committed
146
        {chat.map((value, index) => {
147
          if (!(value.msg === '')) {
Choi Ga Young's avatar
Choi Ga Young committed
148
149
            if (value.sender === "system") {
              return (
Choi Ga Young's avatar
퇴장    
Choi Ga Young committed
150
                <Row style={{ background: "#F5F5F5", border:"none" }}>
Choi Ga Young's avatar
Choi Ga Young committed
151
152
153
154
                  {value.msg}
                </Row>
              )
            } else if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
155
156
157
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
JeongYeonwoo's avatar
JeongYeonwoo committed
158
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
159
160
                  </Col>
                  <Col xs={8}>
JeongYeonwoo's avatar
JeongYeonwoo committed
161
                    <Row><strong>{value.sender}</strong></Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
162
                    <Row className='d-flex flex-wrap-nowrap'>
163
                      <Row className='border' 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
164
                      <Col className='ml-1'>{value.time}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
165
166
                    </Row>
                  </Col>
167
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
168
169
              )
            } else {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
170
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
171
172
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
173
                    <Col className='mr-1'>{value.time}</Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
174
                    <Row className='mr-2' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: "#d6c8e3", borderRadius: 'px', fontSize: 'x-large' }}>{value.msg}</Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
175
                  </Row>
176
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
177
178
179
180
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
181
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
182
        })
183
        }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
184
185
186
187
188
189
190
191
192
193
194
195
196
      </div>
      <div id="chat-low-side" style={{ width: "95%", height: "60px", position: "absolute", bottom: "0", padding: "10px 5px 5px 10px" }}>
        <div id="chat-form" style={{ width: "100%", height: "100%", borderStyle: "solid", borderWidth: "2px", borderColor: "#C1C1C1", borderRadius: "25px", padding: "3px 2px 2px 3px" }}>
          <Form onSubmit={sendMsgCH}>
            <Form.Group style={{ display: "flex", flexDirection: "row", justifyContent: "space-evenly" }}>
              <Form.Control name='chat' type="text" value={inner} onChange={handleChange} style={{ width: "80%", height: "90%", borderColor: "#FFFFFF" }} />
              <Button type="submit" disabled={disabled} style={{ justifyContent: "center", width: "10%", height: "90%", borderRadius: "20px", backgroundColor: "#C1C1C1", borderColor: "#FFFFFF" }}>
                <FiSend size="16px" color="FAFAFA" />
              </Button>
            </Form.Group>
          </Form>
        </div>
      </div>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
197
    </div>
우지원's avatar
ul    
우지원 committed
198
199
200
  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
201

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