Commit ebe36b8d authored by Balasuriya D.A.M.'s avatar Balasuriya D.A.M.

Realtime Typing Functionality

parent 485734fe
......@@ -58,6 +58,9 @@ io.on("connection", (socket) => {
console.log("User Joined Room: " + room);
});
socket.on("typing", (room) => socket.in(room).emit("typing"));
socket.on("stop typing", (room) => socket.in(room).emit("stop typing"));
socket.on("new message", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;
......
......@@ -21,6 +21,8 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
const [loading, setLoading] = useState(false);
const [newMessage, setNewMessage] = useState();
const [socketConnected, setSocketConnected] = useState(false);
const [typing, setTyping] = useState(false);
const [isTyping, setIsTyping] = useState(false);
const toast = useToast();
const { user, selectedChat, setSelectedChat } = ChatState();
......@@ -67,7 +69,10 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
useEffect(() => {
socket = io(ENDPOINT);
socket.emit("setup", user);
socket.on("connection", () => setSocketConnected(true));
socket.on("connected", () => setSocketConnected(true));
socket.on("typing", () => setIsTyping(true));
socket.on("stop typing", () => setIsTyping(false));
}, []);
useEffect(() => {
......@@ -91,6 +96,8 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
const sendMessage = async(event) => {
if (event.key === "Enter" && newMessage) {
//after sending the message should stop the typing
socket.emit("stop typing", selectedChat._id);
try {
const config = {
headers: {
......@@ -133,6 +140,24 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
setNewMessage(e.target.value);
//Typing Indicator Logic
if (!socketConnected) return;
if (!typing) {
setTyping(true);
socket.emit("typing", selectedChat._id);
}
//debouncing function if the user is not typing
let lastTypingTime = new Date().getTime();
var timerLength = 3000;
setTimeout(() => {
var timeNow = new Date().getTime();
var timeDiff = timeNow - lastTypingTime;
if (timeDiff >= timerLength && typing) {
socket.emit("stop typing", selectedChat._id);
setTyping(false);
}
},timerLength);
};
return (
......@@ -196,6 +221,8 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
)}
<FormControl onKeyDown={sendMessage} isRequired mt={3}>
{isTyping ? <div>Loading...</div> : (<></>)}
<Input
variant="filled"
bg="E0E0E0"
......
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