-
Notifications
You must be signed in to change notification settings - Fork 253
Complete chat app with rooms and history #173
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
Open
gmarchese93
wants to merge
3
commits into
mate-academy:master
Choose a base branch
from
gmarchese93:develop
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| <!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8"> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
| <title>Document</title> | ||
| </head> | ||
| <body> | ||
| <div id="root"></div> | ||
| <script type="module" src="./src/main.jsx"></script> | ||
| </body> | ||
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| /* eslint-disable */ | ||
| import { useEffect, useState } from "react"; | ||
| import { MessagesList } from "./components/MessagesList.jsx"; | ||
|
|
||
| const socket = new WebSocket("ws://localhost:3232"); | ||
|
|
||
| export const App = () => { | ||
| const [name, setName] = useState(localStorage.getItem("Name") || ""); | ||
| const [room, setRoom] = useState(""); | ||
| const [newRoomName, setNewRoomName] = useState(""); | ||
| const [rooms, setRooms] = useState([]); | ||
| const [message, setMessage] = useState(""); | ||
| const [messages, setMessages] = useState([]); | ||
|
|
||
| useEffect(() => { | ||
| socket.onmessage = (event) => { | ||
| const data = JSON.parse(event.data); | ||
|
|
||
| if (data.type === "rooms") { | ||
| setRooms(data.list); | ||
| } | ||
|
|
||
| if (data.type === "history") { | ||
| setMessages(data.messages); | ||
| } | ||
|
|
||
| if (data.type === "message") { | ||
| setMessages((prev) => [...prev, data.message]); | ||
| } | ||
| }; | ||
| }, []); | ||
|
|
||
| function saveName() { | ||
| if (!name.trim()) return; | ||
| localStorage.setItem("Name", name); | ||
| } | ||
|
|
||
| function joinRoom(r) { | ||
| setRoom(r); | ||
| setMessages([]); | ||
|
|
||
| socket.send( | ||
| JSON.stringify({ | ||
| type: "join_room", | ||
| name: r, | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| function createRoom() { | ||
| if (!room.trim()) return; | ||
|
|
||
| socket.send( | ||
| JSON.stringify({ | ||
| type: "create_room", | ||
| name: room, | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| function deleteRoom() { | ||
| if (!room) return; | ||
|
|
||
| socket.send( | ||
| JSON.stringify({ | ||
| type: "delete_room", | ||
| name: room, | ||
| }), | ||
| ); | ||
|
|
||
| setRoom(""); | ||
| setMessages([]); | ||
| } | ||
|
|
||
| function renameRoom() { | ||
| if (!room || !newRoomName.trim()) return; | ||
|
|
||
| socket.send( | ||
| JSON.stringify({ | ||
| type: "rename_room", | ||
| oldName: room, | ||
| newName: newRoomName, | ||
| }), | ||
| ); | ||
|
|
||
| setRoom(newRoomName); | ||
| setNewRoomName(""); | ||
| } | ||
|
|
||
| function sendMessage() { | ||
| if (!message.trim()) return; | ||
|
|
||
| socket.send( | ||
| JSON.stringify({ | ||
| type: "message", | ||
| author: name, | ||
| text: message, | ||
| }), | ||
| ); | ||
|
|
||
| setMessage(""); | ||
| } | ||
|
|
||
| return ( | ||
| <div> | ||
| {!name && ( | ||
| <div> | ||
| <input | ||
| placeholder="Your name" | ||
| value={name} | ||
| onChange={(e) => setName(e.target.value)} | ||
| /> | ||
| <button onClick={saveName}>Save</button> | ||
| </div> | ||
| )} | ||
|
|
||
| {name && ( | ||
| <div> | ||
| <h3>Rooms</h3> | ||
| {rooms.map((r) => ( | ||
| <button key={r} onClick={() => joinRoom(r)}> | ||
| {r} | ||
| </button> | ||
| ))} | ||
|
|
||
| <div> | ||
| <input | ||
| placeholder="Room name" | ||
| value={room} | ||
| onChange={(e) => setRoom(e.target.value)} | ||
| /> | ||
| <button onClick={createRoom}>Create</button> | ||
| <button onClick={deleteRoom}>Delete</button> | ||
| </div> | ||
|
|
||
| {room && ( | ||
| <div> | ||
| <input | ||
| placeholder="New room name" | ||
| value={newRoomName} | ||
| onChange={(e) => setNewRoomName(e.target.value)} | ||
| /> | ||
| <button onClick={renameRoom}>Rename</button> | ||
| </div> | ||
| )} | ||
| </div> | ||
| )} | ||
|
|
||
| {room && ( | ||
| <div> | ||
| <input | ||
| placeholder="Message" | ||
| value={message} | ||
| onChange={(e) => setMessage(e.target.value)} | ||
| /> | ||
| <button onClick={sendMessage}>Send</button> | ||
|
|
||
| <MessagesList list={messages} /> | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| export const MessagesList = ({ list }) => { | ||
| return ( | ||
| <div> | ||
| {list.map((m) => ( | ||
| <p key={m.id}> | ||
| <b>{m.author}</b>: {m.text} | ||
| <small> ({new Date(m.time).toLocaleTimeString()})</small> | ||
| </p> | ||
| ))} | ||
| </div> | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import express from 'express'; | ||
| import { WebSocketServer } from 'ws'; | ||
| import http from 'http'; | ||
|
|
||
| import { | ||
| rooms, | ||
| createRoom, | ||
| renameRoom, | ||
| deleteRoom, | ||
| joinRoom, | ||
| } from './websocket.js'; | ||
gmarchese93 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const app = express(); | ||
| const server = http.createServer(app); | ||
|
|
||
| app.use(express.static('src')); | ||
|
|
||
| const wss = new WebSocketServer({ server }); | ||
|
|
||
| function broadcastRoomList() { | ||
| const list = Object.keys(rooms); | ||
| const message = JSON.stringify({ type: 'rooms', list }); | ||
|
|
||
| wss.clients.forEach((client) => { | ||
| client.send(message); | ||
| }); | ||
| } | ||
|
|
||
| wss.on('connection', (ws) => { | ||
| ws.on('message', (raw) => { | ||
| const data = JSON.parse(raw); | ||
|
|
||
| if (data.type === 'create_room') { | ||
| createRoom(data.name); | ||
| broadcastRoomList(); | ||
| } | ||
|
|
||
| if (data.type === 'rename_room') { | ||
| renameRoom(data.oldName, data.newName); | ||
| broadcastRoomList(); | ||
| } | ||
|
|
||
| if (data.type === 'delete_room') { | ||
| deleteRoom(data.name); | ||
| broadcastRoomList(); | ||
| } | ||
|
|
||
| if (data.type === 'join_room') { | ||
| joinRoom(data.name, ws); | ||
|
|
||
| ws.send( | ||
| JSON.stringify({ | ||
| type: 'history', | ||
| messages: rooms[data.name]?.messages || [], | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| if (data.type === 'message') { | ||
| const msg = { | ||
| id: Date.now(), | ||
| author: data.author, | ||
| text: data.text, | ||
| time: new Date().toISOString(), | ||
| }; | ||
|
|
||
| Object.values(rooms).forEach((room) => { | ||
| if (room.users.has(ws)) { | ||
| room.messages.push(msg); | ||
|
|
||
| room.users.forEach((client) => { | ||
| client.send( | ||
| JSON.stringify({ | ||
| type: 'message', | ||
| message: msg, | ||
| }), | ||
| ); | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| broadcastRoomList(); | ||
| }); | ||
|
|
||
| export { server }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,12 @@ | ||
| 'use strict'; | ||
|
|
||
| import { server } from './db.js'; | ||
| import dotenv from 'dotenv'; | ||
|
|
||
| dotenv.config(); | ||
|
|
||
| const PORT = process.env.PORT || 3232; | ||
|
|
||
| server.listen(PORT, () => { | ||
| console.log(`Server running at http://localhost:${PORT}`); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import React from "react"; | ||
| import ReactDOM from "react-dom/client"; | ||
| import { App } from './App'; | ||
|
|
||
| ReactDOM.createRoot(document.getElementById("root")).render( | ||
| <React.StrictMode> | ||
| <App /> | ||
| </React.StrictMode> | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| export const rooms = {}; | ||
|
|
||
| export function createRoom(name) { | ||
| if (!name || rooms[name]) { | ||
| return false; | ||
| } | ||
|
|
||
| rooms[name] = { | ||
| name, | ||
| users: new Set(), | ||
| messages: [], | ||
| }; | ||
|
|
||
| return true; | ||
| } | ||
gmarchese93 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| export function renameRoom(oldName, newName) { | ||
| if (!rooms[oldName] || rooms[newName]) { | ||
| return false; | ||
| } | ||
|
|
||
| rooms[newName] = rooms[oldName]; | ||
| rooms[newName].name = newName; | ||
| delete rooms[oldName]; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| export function deleteRoom(name) { | ||
| if (!rooms[name]) { | ||
| return false; | ||
| } | ||
|
|
||
| delete rooms[name]; | ||
| return true; | ||
| } | ||
|
|
||
| export function joinRoom(roomName, client) { | ||
| if (!rooms[roomName]) { | ||
| return false; | ||
| } | ||
|
|
||
| // remove client from all rooms | ||
| Object.values(rooms).forEach((room) => { | ||
| room.users.delete(client); | ||
| }); | ||
|
|
||
| rooms[roomName].users.add(client); | ||
| return true; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This block of controls has a state management issue. It uses the
roomstate for the input field's value, which is also meant to track the currently joined room. This leads to incorrect behavior for theCreate,Delete, andRenamebuttons.For example:
roomstate becomes 'Room A'.roomstate is now 'Room B'.To fix this, consider using a separate state variable for this input field (e.g.,
roomNameInput). ThecreateRoomfunction should use this new state, whiledeleteRoomandrenameRoomshould operate on theroomstate, which should only represent the currently joined room.