Chat.js 8.16 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
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
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)
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
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
64
    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
    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 (
Soo Hyun Kim's avatar
Soo Hyun Kim committed
128
129
    <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" }}>
Choi Ga Young's avatar
Choi Ga Young committed
130
        <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
131
        <div style={{ justifyContent: "center" }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
132
133
          <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
134
        </div>
Choi Ga Young's avatar
Choi Ga Young committed
135
        <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
136
137
138
139
      </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>
Choi Ga Young's avatar
Choi Ga Young committed
140
141
          <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
142
143
        </div>
        : null}
Soo Hyun Kim's avatar
Soo Hyun Kim committed
144
      <div id="chat-body" style={{ overflow: 'auto', padding: '15px', width: "100%", height: "400px", margin: "1%", background: '' }}>
JeongYeonwoo's avatar
JeongYeonwoo committed
145
        {chat.map((value, index) => {
146
          if (!(value.msg === '')) {
Choi Ga Young's avatar
Choi Ga Young committed
147
148
            if (value.sender === "system") {
              return (
Choi Ga Young's avatar
Choi Ga Young committed
149
                <Row style={{ background: "#F5F5F5", border: "none", justifyContent: "center" }}>
Choi Ga Young's avatar
Choi Ga Young committed
150
151
152
153
                  {value.msg}
                </Row>
              )
            } else if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
154
155
156
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
JeongYeonwoo's avatar
JeongYeonwoo committed
157
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
158
159
                  </Col>
                  <Col xs={8}>
JeongYeonwoo's avatar
JeongYeonwoo committed
160
                    <Row><strong>{value.sender}</strong></Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
161
                    <Row className='d-flex flex-wrap-nowrap'>
162
                      <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
163
                      <Col className='ml-1'>{value.time}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
164
165
                    </Row>
                  </Col>
166
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
167
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
168
169
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
170
171
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
172
                    <Col className='mr-1'>{value.time}</Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
173
                    <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
174
                  </Row>
175
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
176
177
178
179
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
180
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
181
        })
182
        }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
183
184
185
186
187
188
189
      </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" }}>
우지원's avatar
오픈    
우지원 committed
190
                <FiSend size="16px" color="#FAFAFA" />
Soo Hyun Kim's avatar
Soo Hyun Kim committed
191
192
193
194
195
              </Button>
            </Form.Group>
          </Form>
        </div>
      </div>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
196
    </div>
우지원's avatar
ul    
우지원 committed
197
198
199
  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
200

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