Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve sockets #10

Merged
merged 17 commits into from
Jun 17, 2021
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/src/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const Login = (props) => {
className={classes.input}
InputProps={{
endAdornment: (
<InputAdornment component={Link} position="start">
<InputAdornment component={'div'} position="start">
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest using Box here instead of 'div' - since this project uses Material UI, it'd be better to stick to using Material UI components instead of mixing regular jsx in to keep things consistent.

<Link href="#" color="primary">
{"Forgot?"}
</Link>
Expand Down
9 changes: 2 additions & 7 deletions client/src/Signup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React from "react";
import { Redirect, useHistory } from "react-router-dom";
import { connect } from "react-redux";
import {
Expand All @@ -7,7 +7,6 @@ import {
Button,
FormControl,
TextField,
FormHelperText,
Hidden,
} from "@material-ui/core";
import { register } from "./store/utils/thunkCreators";
Expand All @@ -18,7 +17,6 @@ import HomeSideBanner from "./components/HomeSideBanner/HomeSideBanner";
const Login = (props) => {
const history = useHistory();
const { user, register } = props;
const [formErrorMessage, setFormErrorMessage] = useState({});
const classes = useStyles()

const handleRegister = async (event) => {
Expand Down Expand Up @@ -72,7 +70,7 @@ const Login = (props) => {
className={classes.input}
/>
</FormControl>
<FormControl margin='normal' className={classes.full} error={!!formErrorMessage.confirmPassword}>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are the changes in this file related to this PR?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 75 was extraneous code from when there was still a confirm-password field on signup. I realized (after completing the login and signup redesign) that I had left that line there; even though it's a single line, is it generally best practice to just make that change in the login/signup-redesign branch?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally, best practice would be to open a new PR to do cleanup like this. If you want to include it in an unrelated PR like you've done here, it's helpful to reviewers to mention it in the PR description. I wouldn't remove it from this PR at this point.

<FormControl margin='normal' className={classes.full}>
<TextField
aria-label="password"
label="Password"
Expand All @@ -81,9 +79,6 @@ const Login = (props) => {
name="password"
className={classes.input}
/>
<FormHelperText>
{formErrorMessage.confirmPassword}
</FormHelperText>
</FormControl>
<Button
type="submit"
Expand Down
8 changes: 4 additions & 4 deletions client/src/Styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const useStyles = makeStyles({
},
formMessage: {
fontWeight: 900,
['@media (max-width:600px)']: {
'@media (max-width:600px)': {
textAlign: 'center',
},
},
Expand All @@ -73,17 +73,17 @@ const useStyles = makeStyles({
display: 'flex',
flexDirection: 'column',
width: '80%',
['@media (max-width:750px)']: {
'@media (max-width:750px)': {
width: '100%',
},
},
redirectHeader: {
alignItems: 'center',
['@media (max-width:750px)']: {
'@media (max-width:750px)': {
flexDirection: 'column',
justifyContent: 'center',
},
['@media (min-width:750px)']: {
'@media (min-width:750px)': {
justifyContent: 'flex-end',
}
},
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/ActiveChat/ActiveChat.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const mapStateToProps = (state) => {
state.conversations &&
state.conversations.find(
(conversation) => conversation.otherUser.username === state.activeConversation
)
),
};
};

Expand Down
22 changes: 21 additions & 1 deletion client/src/components/ActiveChat/Input.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { Component } from "react";
import { FormControl, FilledInput } from "@material-ui/core";
import { withStyles } from "@material-ui/core/styles";
import { connect } from "react-redux";
import { postMessage } from "../../store/utils/thunkCreators";
import { postMessage, changeTypingStatus } from "../../store/utils/thunkCreators";

const styles = {
root: {
Expand All @@ -17,18 +17,28 @@ const styles = {
},
};

// TO-DO: refactor to use functional components and react hooks
class Input extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
typing: false,
timeout: "",
};
}

handleChange = (event) => {
const timer = setTimeout(this.typingTimeout, 3000)
this.setState({
text: event.target.value,
typing: true,
timeout: clearTimeout(this.state.timeout),
});
this.props.changeTypingStatus(this.props.user, this.props.otherUser.id, this.state.typing)
this.setState({
timeout: timer,
})
};

handleSubmit = async (event) => {
Expand All @@ -43,9 +53,16 @@ class Input extends Component {
await this.props.postMessage(reqBody);
this.setState({
text: "",
timeout: clearTimeout(this.state.timeout),
});
this.typingTimeout()
};

typingTimeout = () => {
this.setState({ typing: false })
this.props.changeTypingStatus(this.props.user, this.props.otherUser.id, this.state.typing)
}

render() {
const { classes } = this.props;
return (
Expand Down Expand Up @@ -77,6 +94,9 @@ const mapDispatchToProps = (dispatch) => {
postMessage: (message) => {
dispatch(postMessage(message));
},
changeTypingStatus: (sender, recipientId, isTyping) =>
dispatch(changeTypingStatus(sender, recipientId, isTyping))

};
};

Expand Down
17 changes: 15 additions & 2 deletions client/src/components/ActiveChat/Messages.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import React, { useMemo } from "react";
import React, { useRef, useEffect } from "react";
import { useSelector } from 'react-redux'
import { Box } from "@material-ui/core";
import { withStyles } from '@material-ui/core/styles'
import { SenderBubble, OtherUserBubble } from "../ActiveChat";
import { SenderBubble, OtherUserBubble, } from "../ActiveChat";
import moment from "moment";
import TypingIndicator from './TypingIndicator'

const styles = {
root: {
Expand All @@ -16,8 +18,15 @@ const styles = {
};

const Messages = (props) => {
const typingStatus = useSelector(state => state.conversations.find(
sebthtan marked this conversation as resolved.
Show resolved Hide resolved
(conversation) => conversation.otherUser.username === state.activeConversation).typingStatus)
const { classes } = props
const { messages, otherUser, userId } = props;
const bottom = useRef(null)

useEffect(() => {
bottom.current.scrollIntoView({ behavior: 'smooth' })
}, [typingStatus, messages.length])

return (
<Box className={classes.root}>
Expand All @@ -30,6 +39,10 @@ const Messages = (props) => {
<OtherUserBubble key={message.id} text={message.text} time={time} otherUser={otherUser} />
);
})}
{typingStatus &&
<TypingIndicator otherUser={otherUser} />
}
<div ref={bottom}></div>
</Box>
);
};
Expand Down
81 changes: 81 additions & 0 deletions client/src/components/ActiveChat/TypingIndicator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Box, Typography, Avatar } from "@material-ui/core";

const useStyles = makeStyles(() => ({
root: {
display: "flex"
},
avatar: {
height: 30,
width: 30,
marginRight: 11,
marginTop: 6
},
usernameDate: {
fontSize: 11,
color: "#BECCE2",
fontWeight: "bold",
marginBottom: 5
},
bubble: {
backgroundImage: "linear-gradient(225deg, #6CC1FF 0%, #3A8DFF 100%)",
borderRadius: "0 10px 10px 10px",
padding: '10px 15px',
display: 'flex',
},
text: {
fontSize: 14,
fontWeight: "bold",
color: "#FFFFFF",
letterSpacing: -0.2,
padding: 8
},
dot: {
height: '10px',
width: '10px',
borderRadius: '100%',
display: 'inline-block',
backgroundColor: 'rgb(250, 250, 250, 0.6)',
margin: '2px',
animation: '$typing-dot 1.2s ease-in-out 1.2s infinite',
"&:nth-of-type(2)": {
animationDelay: '0.15s',
},
"&:nth-of-type(3)": {
animationDelay: '0.25s',
},
},
'@keyframes typing-dot': {
'15%': {
transform: 'translateY(-35%)',
opacity: 0.1
},
'30%': {
transform: 'translateY(0%)',
opacity: 1,
},
},
}));

const TypingIndicator = (props) => {
const classes = useStyles();
const { otherUser } = props;
return (
<Box className={classes.root}>
<Avatar alt={otherUser.username} src={otherUser.photoUrl} className={classes.avatar}></Avatar>
<Box>
<Typography className={classes.usernameDate}>
{otherUser.username}
</Typography>
<Box className={classes.bubble}>
<Typography className={classes.dot}></Typography>
<Typography className={classes.dot}></Typography>
<Typography className={classes.dot}></Typography>
</Box>
</Box>
</Box>
);
};

export default TypingIndicator;
10 changes: 9 additions & 1 deletion client/src/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import {
setNewMessage,
removeOfflineUser,
addOnlineUser,
displayTypingStatus,
} from "./store/conversations";

const socket = io(window.location.origin);
// autoConnect set to false so that the connection is not established immediately.
// Connection will be manually established using socket.connect() in login/register thunks.
const socket = io(window.location.origin, { autoConnect: false });

socket.on("connect", () => {
console.log("connected to server");
Expand All @@ -18,9 +21,14 @@ socket.on("connect", () => {
socket.on("remove-offline-user", (id) => {
store.dispatch(removeOfflineUser(id));
});

socket.on("new-message", (data) => {
store.dispatch(setNewMessage(data.message, data.sender));
});

socket.on('typing-status', (data) => {
store.dispatch(displayTypingStatus(data.sender, data.isTyping))
})
});

export default socket;
14 changes: 13 additions & 1 deletion client/src/store/conversations.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
addSearchedUsersToStore,
removeOfflineUserFromStore,
addMessageToStore,
changeConvoTypingStatus,
setConvosToStore,
} from "./utils/reducerFunctions";

// ACTIONS
Expand All @@ -15,6 +17,7 @@ const REMOVE_OFFLINE_USER = "REMOVE_OFFLINE_USER";
const SET_SEARCHED_USERS = "SET_SEARCHED_USERS";
const CLEAR_SEARCHED_USERS = "CLEAR_SEARCHED_USERS";
const ADD_CONVERSATION = "ADD_CONVERSATION";
const SET_TYPING_STATUS = 'SET_TYPING_STATUS'

// ACTION CREATORS

Expand Down Expand Up @@ -59,6 +62,13 @@ export const clearSearchedUsers = () => {
};
};

export const displayTypingStatus = (sender, isTyping) => {
return {
type: SET_TYPING_STATUS,
payload: { sender, isTyping }
}
}

// add new conversation when sending a new message
export const addConversation = (recipientId, newMessage) => {
return {
Expand All @@ -72,7 +82,7 @@ export const addConversation = (recipientId, newMessage) => {
const reducer = (state = [], action) => {
switch (action.type) {
case GET_CONVERSATIONS:
return action.conversations;
return setConvosToStore(state, action.conversations);
case SET_MESSAGE:
return addMessageToStore(state, action.payload);
case ADD_ONLINE_USER: {
Expand All @@ -91,6 +101,8 @@ const reducer = (state = [], action) => {
action.payload.recipientId,
action.payload.newMessage
);
case SET_TYPING_STATUS:
return changeConvoTypingStatus(state, action.payload)
default:
return state;
}
Expand Down
32 changes: 32 additions & 0 deletions client/src/store/utils/reducerFunctions.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
export const setConvosToStore = (state, conversations) => {
const convosMap = {}
const newState = state.map(convo => {
convosMap[convo.id] = convo
const convoCopy = { ...convo }
return convoCopy
})

conversations.forEach(convo => {
if (Object.keys(convosMap).includes(convo.id.toString())) {
newState[newState.indexOf(convosMap[convo.id])] = convo
} else {
newState.push(convo)
}
})

return newState
}

export const addMessageToStore = (state, payload) => {
const { message, sender } = payload;
// if sender isn't null, that means the message needs to be put in a brand new convo
Expand Down Expand Up @@ -81,3 +100,16 @@ export const addNewConvoToStore = (state, recipientId, message) => {
}
});
};

export const changeConvoTypingStatus = (state, payload) => {
const { sender, isTyping } = payload
return state.map(convo => {
if (convo.otherUser.id === sender.id) {
const convoCopy = { ...convo }
convoCopy.typingStatus = isTyping
return convoCopy
} else {
return convo
}
})
}
Loading