Chat.js 8.52 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: ''
}
15

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

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

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

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

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

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

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

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

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

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

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

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

  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)
    }

80
  }
Choi Ga Young's avatar
Choi Ga Young committed
81

82

Choi Ga Young's avatar
Choi Ga Young committed
83
  function handleClick() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
84
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
85
    props.setRecievedMsg('')
Choi Ga Young's avatar
Choi Ga Young committed
86
    props.handleChatc()
JeongYeonwoo's avatar
JeongYeonwoo committed
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

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

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

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

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


우지원's avatar
ul    
우지원 committed
144
  return (
Soo Hyun Kim's avatar
Soo Hyun Kim committed
145
    <div id="chat" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', width: "100%", height: "90vh", position: "relative" }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
146
      <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
147
        <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
148
        <div style={{ justifyContent: "center" }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
149
150
          <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
151
        </div>
Choi Ga Young's avatar
Choi Ga Young committed
152
        <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
153
154
155
156
      </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
157
158
          <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
159
160
        </div>
        : null}
Soo Hyun Kim's avatar
Soo Hyun Kim committed
161
      <div id="chat-body" style={{ overflow: 'auto', padding: '15px', width: "100%", height: "75%", margin: "1%", background: '' }}>
JeongYeonwoo's avatar
JeongYeonwoo committed
162
        {chat.map((value, index) => {
163
          if (!(value.msg === '')) {
Choi Ga Young's avatar
Choi Ga Young committed
164
165
            if (value.sender === "system") {
              return (
Choi Ga Young's avatar
Choi Ga Young committed
166
                <Row style={{ background: "#F5F5F5", border: "none", justifyContent: "center" }}>
Choi Ga Young's avatar
Choi Ga Young committed
167
168
169
170
                  {value.msg}
                </Row>
              )
            } else if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
171
              return (
우지원's avatar
chat    
우지원 committed
172
                <Row key={index} className='d-flex flex-wrap-nowrap mt-2' style={{ width: "95%", maxWidth: '95%' }}>
우지원's avatar
우지원 committed
173
                  <Col xs="auto">
우지원's avatar
chat    
우지원 committed
174
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "55px", height: "55px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
175
                  </Col>
우지원's avatar
chat    
우지원 committed
176
                  <Col className="ml-2">
JeongYeonwoo's avatar
JeongYeonwoo committed
177
                    <Row><strong>{value.sender}</strong></Row>
우지원's avatar
chat    
우지원 committed
178
                    <Row xs="auto" className='d-flex flex-wrap-nowrap'>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
179
                      <Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: '#f1ebf7', borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Row>
우지원's avatar
chat    
우지원 committed
180
                      <Col className="ml-1">{value.time}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
181
182
                    </Row>
                  </Col>
183
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
184
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
185
186
            } else {
              return ( //내가 보낸 메시지
우지원's avatar
chat    
우지원 committed
187
                <Row key={index} className='mt-2 justify-content-end' style={{ width: "100%" }}>
JeongYeonwoo's avatar
JeongYeonwoo committed
188
                  <Row className='d-flex flex-wrap-nowrap' >
우지원's avatar
우지원 committed
189
                    <Col xs="auto" className="ml-3">{value.time}</Col>
우지원's avatar
chat    
우지원 committed
190
                    <Col className='mr-1' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: "#d6c8e3", borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
191
                  </Row>
192
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
193
194
195
196
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
197
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
198
        })
199
        }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
200
201
202
203
204
205
206
      </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
207
                <FiSend size="16px" color="#FAFAFA" />
Soo Hyun Kim's avatar
Soo Hyun Kim committed
208
209
210
211
212
              </Button>
            </Form.Group>
          </Form>
        </div>
      </div>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
213
    </div>
우지원's avatar
ul    
우지원 committed
214
215
216
  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
217

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