Commit 35899ce6 authored by Soo Hyun Kim's avatar Soo Hyun Kim
Browse files

Merge remote-tracking branch 'origin/young' into sooModalTest

parents f8a30995 918ba292
node_modules node_modules
package-lock.json package-lock.json
uploads
\ No newline at end of file
import axios from 'axios';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Form, Button, Row } from 'react-bootstrap'; import { Form, Button, Row, Image, Col, Container } from 'react-bootstrap';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
function Chat(props) { function Chat(props) {
let defaultname = sessionStorage.getItem('name'); // let defaultname = sessionStorage.getItem('name');
const [inner, setInner] = useState(['']) const [inner, setInner] = useState([''])
const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지 const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지
const [disabled, setDisabled] = useState(true)
const [user, setUser] = useState('')
const [error, setError] = useState('');
const userId = isAuthenticated()
async function getProfile(userId) {
try {
const response = await axios.get(`/users/${userId}`)
setUser(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
setInner(e.target.value) setInner(e.target.value)
console.log(e.target.value)
setDisabled(false)
} }
function sendMsgCH(e) { function sendMsgCH(e) {
...@@ -18,40 +36,92 @@ function Chat(props) { ...@@ -18,40 +36,92 @@ function Chat(props) {
props.setSingleChat(inner) props.setSingleChat(inner)
props.sendMsg(e) props.sendMsg(e)
setInner('') setInner('')
setDisabled(true)
console.log(chat)
} }
useEffect(() => {
getProfile(userId)
}, [userId])
useEffect(() => { useEffect(() => {
setChat([...chat, props.singleChat]) setChat([...chat, props.singleChat])
console.log('UseEffect singlechat', chat)
// check()
}, [props.singleChat]) }, [props.singleChat])
useEffect(() => { useEffect(() => {
setChat([...chat, props.recievedMsg]) setChat([...chat, props.recievedMsg])
console.log('UseEffect recievechat', chat)
}, [props.recievedMsg]) }, [props.recievedMsg])
return (
<div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}> // function check() {
<h2>현재 {props.roomName} 입니다.</h2> // // if (chat[chat.length-1].user ===chat[chat.length-2].user){ //마지막보낸거랑 그 전꺼랑 보낸사람이 같은지 비교
{ chat.map((value, index) => { // if (chat.length === 2) {
if (!(value=='')) { // setHidden(false)
// console.log(`value=${value}=`) // } else {
return <Row key={index} className='ml-3'> // setHidden(true)
{props.roomName}에서 {defaultname}님이 보낸 메세지 : {value} // }
// console.log(hidden)
// }
const time = new Date().toLocaleTimeString()
return (
<div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
<h2>해당 방에 대한 참여코드는 {props.roomCode} 입니다.</h2>
{/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */}
{chat.map((value, index) => {
if (!(value == '')) {
return (
<Row key={index} className='m-1 ml-3' >
<Col xs={2}>
{user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "50px", height: "50px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "50px", height: "50px" }} roundedCircle />}
</Col>
<Col xs={8}>
<Row><strong>{user.nickname} {index}</strong></Row>
<Row className='d-flex flex-wrap-nowrap'>
<Col className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Col>
<Col className='ml-4'>{new Date().toLocaleTimeString()}</Col>
</Row> </Row>
</Col>
</Row>
)
} else { } else {
return null return null
} }
})} })
}
{/* 내가 보낸 메세지 띄우기 */}
{chat.map((value, index) => {
if (!(value == '')) {
return (
<Row key={index} className='m-1 mr-4 justify-content-end'>
<div className='d-flex flex-wrap-nowrap' >
<Row className='mr-4'>{time}</Row>
<Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
</div>
</Row>
)
} else {
return null
}
})
}
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button> <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<Form onSubmit={sendMsgCH}> <Form onSubmit={sendMsgCH}>
<Form.Group> <Form.Group className='d-flex flex-wrap-nowrap justify-content-center ml-2 mr-2'>
<Form.Control name='chat' type="text" value={inner} onChange={handleChange} /> <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
</Form.Group> <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
<Button variant="primary" type="submit">
전송 전송
</Button> </Button>
</Form.Group>
</Form> </Form>
</div> </div >
); );
......
import React, { useState } from 'react';
import { Form, Row, Col, Button } from 'react-bootstrap'
function ChatForm(props) {
const INIT_SAYING = ''
const [saying, setSaying] = useState(INIT_SAYING);
function handleChange(event) {
const { name, value } = event.target
setSaying(value)
console.log(saying)
}
function handleSubmit(event) {
event.preventDefault()
// const response = await axios.post('chat/makeChat', chatR)
props.setSingleChat()
setSaying(INIT_SAYING)
}
return (
<Form onSubmit={handleSubmit}>
<Row>
<Col>
<Form.Group>
<Form.Control name='chat' type='text' onChange={handleChange}>chat</Form.Control>
</Form.Group>
</Col>
<Col>
<Form.Group>
<Button type="submit">send</Button>
</Form.Group>
</Col>
</Row>
</Form>
)
}
export default ChatForm
\ No newline at end of file
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { ListGroup, Row, Col } from 'react-bootstrap'; import { ListGroup } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
function ClosedList(props) { function ClosedList(props) {
...@@ -10,32 +10,24 @@ function ClosedList(props) { ...@@ -10,32 +10,24 @@ function ClosedList(props) {
getClosedList(); getClosedList();
}, []); }, []);
const userId = sessionStorage.getItem('userId');
async function getClosedList() { async function getClosedList() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
console.log('id가져오기', userid)
let res = await axios.get('/room/closedlist', { params: { '_id': userid } }) let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
console.log('가져온거', res)
setList(res.data) setList(res.data)
} }
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
console.log(e.target.name) const roomCode = e.target.name
console.log(e.target) props.enterChatRoom(roomCode)
const roomName = e.target.name props.setRoomCode(roomCode)
props.enterChatRoom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
} }
//user.hasOwnProperty('이름');
return ( return (
<div> <div>
{list.map((item, index) => {list.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomName}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
import React, { useState } from 'react' import React, { useState } from 'react'
import axios from 'axios'; import axios from 'axios';
import { Row, Col, Modal, Button, Form, Alert } from 'react-bootstrap'; import { Row, Col, Modal, Button, Form } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
......
...@@ -11,15 +11,14 @@ function OpenList(props) { ...@@ -11,15 +11,14 @@ function OpenList(props) {
async function getOpenList() { async function getOpenList() {
let res = await axios.get('/room/openlist') let res = await axios.get('/room/openlist')
console.log('가져온거o', res)
setOpenlist(res.data) setOpenlist(res.data)
} }
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
const roomName = e.target.name const roomCode = e.target.name
props.enterChatRoom(roomName) // 각각의 room으로 들어가도록 설정해야 함 props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName) props.setRoomCode(roomCode)
// props.clearChat() // props.clearChat()
} }
...@@ -27,7 +26,7 @@ function OpenList(props) { ...@@ -27,7 +26,7 @@ function OpenList(props) {
<div> <div>
{openlist.map((item, index) => {openlist.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomName}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
//로그인 한 사람만 route로 이동할 수 있도록 함
import React from 'react' import React from 'react'
import { Redirect, Route } from 'react-router-dom' import { Redirect, Route } from 'react-router-dom'
import { isAuthenticated } from '../utils/auth' import { isAuthenticated } from '../utils/auth'
function PrivateRoute({path, children}) { function PrivateRoute({path, children}) {
if (isAuthenticated()) { if (isAuthenticated()) {
//로그인이 됬을 시 정상적으로 작동
return ( return (
<Route path={path}> <Route path={path}>
{children} {children}
</Route> </Route>
) )
} else { } else {
//로그인이 되지 않았을 시 로그인페이지로 이동
return ( return (
<Redirect to='./login' /> <Redirect to='./login' />
) )
......
...@@ -20,9 +20,12 @@ function Home() { ...@@ -20,9 +20,12 @@ function Home() {
//소켓 //소켓
const [singleChat, setSingleChat] = useState('') const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('') const [recievedMsg, setRecievedMsg] = useState('')
const [roomName, setRoomName] = useState('')
const [roomCode, setRoomCode] = useState('') const [roomCode, setRoomCode] = useState('')
//방참가
const [roomName, setRoomName] = useState('')
const handleCloseModal = () => setShowModal(false); const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true); const handleShowModal = () => setShowModal(true);
const handleCloseEnter = () => setEnter(false); const handleCloseEnter = () => setEnter(false);
...@@ -45,7 +48,7 @@ function Home() { ...@@ -45,7 +48,7 @@ function Home() {
useEffect(() => { useEffect(() => {
if (!(singleChat == '')) { if (!(singleChat == '')) {
socket.emit("chat", { socket.emit("chat", {
roomName: roomCode, roomInfo: roomCode,
msg: singleChat msg: singleChat
}) })
setSingleChat(['']) setSingleChat([''])
...@@ -67,15 +70,15 @@ function Home() { ...@@ -67,15 +70,15 @@ function Home() {
<Col className="list" md={5}> <Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example"> <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} > <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatRoom={enterChatRoom} setRoomName={setRoomName}/> <ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
</Tab> </Tab>
<Tab eventKey="open" title="공개방" > <Tab eventKey="open" title="공개방" onClick={handleChato}>
<OpenList enterChatRoom={enterChatRoom} setRoomName={setRoomName}/> <OpenList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
<Col style={{ padding: "0" }}> <Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomName={roomName} /> : null} {chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomCode={roomCode} /> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}> <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block> <Button variant="primary" onClick={handleShowModal} size="lg" block>
......
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import { Image, Button, Container, Form, Row, Col, Dropdown } from 'react-bootstrap'; import { Image, Button, Container, Form, Row, Col } from 'react-bootstrap';
import { BrowserRouter as Link } from 'react-router-dom'; import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
...@@ -76,20 +76,6 @@ function ProfilePage() { ...@@ -76,20 +76,6 @@ function ProfilePage() {
getProfile(userId) getProfile(userId)
}, [userId]) }, [userId])
// const [img, setImg] = useState('')
// function bbb(e) {
// const { name } = e.target
// let reader = new FileReader();
// reader.onload = function (e){
// console.log(e.target.result)
// // setImg(e.target.result)
// // setProfileimg
// // console.log(user,name)
// setUser({...user, [name]: e.target.result})
// };
// reader.readAsDataURL(e.target.files[0])
// )
return ( return (
<> <>
<Menu /> <Menu />
...@@ -98,8 +84,6 @@ function ProfilePage() { ...@@ -98,8 +84,6 @@ function ProfilePage() {
<Col sm={4}> <Col sm={4}>
<Row className='justify-content-center'> <Row className='justify-content-center'>
{user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "300px", height: "300px" }} roundedCircle />} {user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "300px", height: "300px" }} roundedCircle />}
{/* {user.profileimg ? <><Image id='profileimg' src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle hidden={!hidden}/> */}
{/* <Image id='profileimg' src={user.profileimg} style={{ width: "300px", height: "300px" }} roundedCircle hidden={hidden}/></> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "300px", height: "300px" }} roundedCircle />} */}
</Row> </Row>
<Row className='ml-3 mt-3 justify-content-center'> <Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex"> <Form className="d-flex">
...@@ -109,17 +93,6 @@ function ProfilePage() { ...@@ -109,17 +93,6 @@ function ProfilePage() {
</Form.Group> </Form.Group>
</Form> </Form>
</Row> </Row>
{/*
{img?<Image src={img}/> : <h2>아직입니다.</h2>}
<Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex">
<Form.Group>
<Form.Label>프로필 사진 변경</Form.Label>
<Form.Control type='file' name='profileimg' onChange={bbb} accept='image/*' />
</Form.Group>
</Form>
</Row> */}
</Col> </Col>
<Col sm={8}> <Col sm={8}>
<Row className='m-5 justify-content-center'> <Row className='m-5 justify-content-center'>
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css'; import './index.css';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
import SignUpPage from './Pages/SignUpPage'; import SignUpPage from './Pages/SignUpPage';
import ProfilePage from './Pages/ProfilePage'; import ProfilePage from './Pages/ProfilePage';
......
...@@ -21,16 +21,15 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -21,16 +21,15 @@ io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id) console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때 socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
let roomName=data; console.log('join_data확인',data)
socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴 let roomInfo=data;
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
}); });
// socket.on('chat', (data)=>{
// io.to(data.roomName).emit('chat',data.msg); //roomName에 존재하는 모든 소켓들에게
// })
socket.on('chat', (data) => { socket.on('chat', (data) => {
socket.broadcast.emit('sendedMSG', data.msg ); // everyone gets it but the sender console.log('roomname확인', data)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.msg ); // sender 제외 특정 방으로
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
...@@ -39,8 +38,6 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -39,8 +38,6 @@ io.on("connection", (socket) => { // 기본 연결
}); });
// app.use(express.json())
//이부분을 body 파싱함
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(cors()); app.use(cors());
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment