Skip to content

Commit

Permalink
Changed the messaging UI
Browse files Browse the repository at this point in the history
  • Loading branch information
Somnath-Chattaraj committed Oct 6, 2024
1 parent 8ba794a commit a1468d4
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 91 deletions.
4 changes: 2 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
"eslint-plugin-react": "^7.34.3",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"postcss": "^8.4.40",
"tailwindcss": "^3.4.7",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13",
"vite": "^5.3.4"
}
}
202 changes: 119 additions & 83 deletions frontend/src/components/chatroomui/chatroom.jsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,81 @@
import React from "react";
import React, { useContext, useEffect, useRef, useState } from "react";
import { chatRoomApi } from "../contexts/chatRoomApi";
import { useContext,useEffect, useState } from "react";
import useWebSocket from "react-use-websocket"
import useWebSocket from "react-use-websocket";
import { ReadyState } from "react-use-websocket";
import { Navigate } from "react-router-dom";
const Chatroom = ()=>{
const { roomId,userId } = useContext(chatRoomApi);

const Chatroom = () => {
const { roomId, userId } = useContext(chatRoomApi);
const [allMsg, setAllMsg] = useState([]);
const [myMsg,setMyMsg] = useState("");
//making the connections
const { sendJsonMessage, lastMessage, lastJsonMessage, readyState } = useWebSocket('ws://localhost:8080')
//initial query to join the room
const [myMsg, setMyMsg] = useState("");
const messageEndRef = useRef(null); // For auto-scroll

// WebSocket connection
const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket('ws://localhost:8080');

// Initial query to join the room
useEffect(() => {
console.log(roomId);
const tosend = {
type: "joinRoom",
data: {
userId: userId,
roomId: roomId,
}
}
};
sendJsonMessage(tosend);
return ()=>{
}, [roomId, userId, sendJsonMessage]);

}
},[]);
//checking on last message
// Handling incoming messages
useEffect(() => {
if (lastJsonMessage != null) {
if (lastJsonMessage.type == "error") {
alert("Room not connected...")
}
if (lastJsonMessage.type == "newMessage") {
if(lastJsonMessage.data.roomId == roomId)
{
const data = lastJsonMessage.data.message;
setAllMsg(prev => {
return prev.concat(
{
senderId: data.senderId,
message: data.content,
at:data.timestamp,
}
);
})
}
if (lastJsonMessage !== null) {
if (lastJsonMessage.type === "error") {
alert("Room not connected...");
} else if (lastJsonMessage.type === "newMessage" && lastJsonMessage.data.roomId === roomId) {
const data = lastJsonMessage.data.message;
setAllMsg(prev => [...prev, {
senderId: data.senderId,
message: data.content,
at: data.timestamp,
}]);
}
}
}, [lastJsonMessage])
}, [lastJsonMessage, roomId]);

// Auto-scroll to the bottom when messages are updated
useEffect(() => {
if (messageEndRef.current) {
messageEndRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [allMsg]);

// Submit message function
const submit = () => {
const tosend = {
type: "sendMessage",
data: {
roomId: roomId,
userId: userId,
message: myMsg
}
};
sendJsonMessage(tosend);
setAllMsg(prev => [...prev, {
senderId: "you",
message: myMsg,
at: new Date().toISOString(),
}]);
setMyMsg(""); // Clear input field
};

// Format date
const formatDate = (isoString) => {
const date = new Date(isoString);
return new Intl.DateTimeFormat('en-US', {
weekday: 'short',
hour: 'numeric',
minute: 'numeric',
hour12: true
}).format(date);
};

const constatus = {
[ReadyState.CONNECTING]: 'Connecting',
Expand All @@ -57,55 +85,63 @@ const Chatroom = ()=>{
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];

const submit = ()=>{
const tosend = {
type:"sendMessage",
data : {
roomId:roomId,
userId:userId,
message:myMsg
}}
sendJsonMessage(tosend,true);
setAllMsg(prev => {
return prev.concat(
{
senderId: "you",
message: tosend.data.message,
at: Date().toString(),
}
);})
}

return (
<div>
<div>
<h4>
connection status {constatus}
<div>
room id : {roomId? roomId : "null"}
<div className="min-h-screen flex flex-col bg-gradient-to-br from-gray-800 to-slate-600 p-4 text-white">
<div className="max-w-4xl mx-auto w-full flex-grow flex flex-col bg-slate-900/80 rounded-lg shadow-lg p-6 space-y-6">
{/* Header */}
<div className="flex justify-between items-center mb-4">
<h4 className="text-yellow-300 text-lg font-semibold">
Connection Status: <span className="font-normal">{constatus}</span>
</h4>
<div className="text-gray-300">
Room ID: <span className="font-semibold">{roomId || "null"}</span>
</div>
</h4>
</div>
<div>
lastMessage:{JSON.stringify(lastJsonMessage)}
</div>
<div>
<h1>Messages:</h1>
{allMsg.length? allMsg.map((data,index)=>{
return (
<div id={index.toString()}>
<div>senderId : <b>{data.senderId}</b></div>
<div>massage: <b>{data.message}</b></div>
<div>at : {data.at}</div>
</div>
)
}):"no message"}
</div>
<div>
<input type="text" placeholder="chat" value={myMsg} onChange={e=>setMyMsg(e.target.value)}/>
<button onClick={submit}>send</button>
</div>

{/* Messages */}
<div className="flex-grow overflow-y-auto p-4 bg-gray-800 rounded-lg shadow-inner max-h-full scrollbar-thin scrollbar-thumb-gray-500">
{allMsg.length ? (
allMsg.map((data, index) => (
data.senderId !== userId ? (
<div
key={index}
className={`p-4 rounded-lg shadow-md space-y-2 ${
data.senderId === "you" ? "bg-green-700 ml-auto" : "bg-slate-700 mr-auto"
} max-w-xs`}
>
<div>{data.senderId === "you" ? "You" : data.senderId}</div>
<div>
<b>{data.message}</b>
</div>
<div className="text-sm text-gray-400">Sent at: {formatDate(data.at)}</div>
</div>
) : null
))
) : (
<div className="text-gray-400">No messages yet</div>
)}
<div ref={messageEndRef}></div>
</div>

{/* Input Section */}
<div className="mt-4 flex space-x-4 items-center">
<input
type="text"
placeholder="Type a message..."
value={myMsg}
onChange={(e) => setMyMsg(e.target.value)}
className="flex-1 p-3 rounded-lg bg-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-yellow-400"
/>
<button
onClick={submit}
className="bg-yellow-400 text-slate-800 p-3 rounded-lg shadow-lg font-semibold hover:bg-yellow-300 transition-colors"
>
Send
</button>
</div>
</div>
</div>
)
}
export default Chatroom;
);
};

export default Chatroom;
1 change: 1 addition & 0 deletions frontend/src/components/routes/mainroute.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createBrowserRouter, Navigate } from "react-router-dom";
import { Mainbuttons, Createroom, Joinroom } from "../chatroomui/main";
import Chatroom from "../chatroomui/chatroom";
import Chatroom1 from "../chatroomui/chatroom1";
import { Outlet } from "react-router-dom";
import { chatRoomApi } from "../contexts/chatRoomApi";
import { useState } from "react";
Expand Down
3 changes: 3 additions & 0 deletions frontend/tailwind.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
"./src/components/chatroomui/*.{js,ts,jsx,tsx}",

],
theme: {
extend: {},
},
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
plugins: [],
}
16 changes: 10 additions & 6 deletions frontend/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "tailwindcss";
export default defineConfig({
plugins: [react()],
})
plugins: [react()],
css: {
postcss: {
plugins: [tailwindcss()],
},
},
});

0 comments on commit a1468d4

Please sign in to comment.