diff --git a/modules/room/components/MousePosition.tsx b/modules/room/components/MousePosition.tsx index ee89dc5..258d72c 100644 --- a/modules/room/components/MousePosition.tsx +++ b/modules/room/components/MousePosition.tsx @@ -3,7 +3,6 @@ import { useBoardPosition } from "../hooks/useBoardPosition"; import { useInterval, useMouse } from "react-use"; import { socket } from "@/common/lib/socket"; import { motion } from "framer-motion"; -import { BsCursorFill } from "react-icons/bs"; import { getPos } from "@/common/lib/getPos"; // To track and emit mouse position changes via socket @@ -28,8 +27,7 @@ export const MousePosition = () => { animate={{ x: docX + 15, y: docY + 15 }} transition={{ duration: 0.05, ease: "linear" }} > - {getPos(docX, x).toFixed(0)} | {getPos(docY, y).toFixed(0)} ); -}; +}; \ No newline at end of file diff --git a/modules/room/components/MouseRenderer.tsx b/modules/room/components/MouseRenderer.tsx index 7635898..a8b0ca9 100644 --- a/modules/room/components/MouseRenderer.tsx +++ b/modules/room/components/MouseRenderer.tsx @@ -2,16 +2,17 @@ import { socket } from "@/common/lib/socket"; import { useEffect, useState } from "react"; import UserMouse from "./UserMouse"; import { useUserIds } from "@/common/recoil/users"; -//error prone + export const MouseRenderer = () => { - const userIds= useUserIds(); + const userIds = useUserIds(); -return ( - <> - {userIds.map((userId)=>{ - return ; - })} - -); + return ( + <> + {userIds.map((userId) => ( + + ))} + + ); }; -export default MouseRenderer; + +export default MouseRenderer; \ No newline at end of file diff --git a/modules/room/components/UserMouse.tsx b/modules/room/components/UserMouse.tsx index c4ab4c5..8a7d73f 100644 --- a/modules/room/components/UserMouse.tsx +++ b/modules/room/components/UserMouse.tsx @@ -4,7 +4,6 @@ import { socket } from "@/common/lib/socket"; import { motion } from "framer-motion"; import { BsCursorFill } from "react-icons/bs"; - //cursor issue const UserMouse = ({ userId }: { userId: string }) => { const boardPos = useBoardPosition(); @@ -13,11 +12,16 @@ const UserMouse = ({ userId }: { userId: string }) => { const [pos, setPos] = useState({ x: -1, y: -1 }); useEffect(() => { - socket.on("mouse_moved", (newX, newY, socketIdMoved) => { + const handleMouseMove = (newX: number, newY: number, socketIdMoved: string) => { if (socketIdMoved === userId) { setPos({ x: newX, y: newY }); } - }); + }; + + socket.on("mouse_moved", handleMouseMove); + return () => { + socket.off("mouse_moved", handleMouseMove); + }; }, [userId]); useEffect(() => { @@ -32,7 +36,7 @@ const UserMouse = ({ userId }: { userId: string }) => { return ( diff --git a/modules/room/hooks/Canvas.hooks.ts b/modules/room/hooks/Canvas.hooks.ts index f03c58f..88956fc 100644 --- a/modules/room/hooks/Canvas.hooks.ts +++ b/modules/room/hooks/Canvas.hooks.ts @@ -71,10 +71,11 @@ export const useDraw = ( ctx.closePath(); setDrawing(false); - const move: Move= { - path: moves, options - } - + const move: Move = { + path: moves, + options + }; + savedMoves.push(move); socket.emit("draw", move); @@ -102,81 +103,78 @@ export const useDraw = ( // Hook to listen for user draw & undo events export const useSocketDraw = ( ctx: CanvasRenderingContext2D | undefined, - drawing : boolean, + drawing: boolean, handleEnd: () => void ) => { const setUsers = useSetRecoilState(usersAtom); - useEffect(()=> { - socket.on("joined", (roomJSON)=> { - const room: Room= new Map(JSON.parse(roomJSON)); + useEffect(() => { + socket.on("joined", (roomJSON) => { + const room: Room = new Map(JSON.parse(roomJSON)); - room.forEach((userMoves, userId)=> { - if(ctx) userMoves.forEach((move)=> handleMove(move, ctx)); + room.forEach((userMoves, userId) => { + if (ctx) userMoves.forEach((move) => handleMove(move, ctx)); handleEnd(); - setUsers((prevUsers)=> ({...prevUsers, [userId]: userMoves})); + setUsers((prevUsers) => ({ ...prevUsers, [userId]: userMoves })); }); }); return () => { socket.off("joined"); } - },[ctx, handleEnd, setUsers]); + }, [ctx, handleEnd, setUsers]); useEffect(() => { let movesToDrawLater: Move | undefined; - let userIdLater= ""; + let userIdLater = ""; socket.on("user_draw", (move, userId) => { if (ctx && !drawing) { handleMove(move, ctx); - + setUsers((prevUsers) => { const newUsers = { ...prevUsers }; - // error maybe here if (newUsers[userId]) newUsers[userId] = [...newUsers[userId], move]; return newUsers; }); - }else { + } else { movesToDrawLater = move; userIdLater = userId; } }); - - return () => { socket.off("user_draw"); - if(movesToDrawLater && userIdLater && ctx){ - handleMove(movesToDrawLater, ctx); - handleEnd(); - setUsers((prevUsers) => { - const newUsers = { ...prevUsers }; - newUsers[userIdLater]= [ - ...newUsers[userIdLater], movesToDrawLater as Move]; - return newUsers; - }) - } - }; - }, [ctx, handleEnd, setUsers, drawing ]); - - useEffect(()=> { - socket.on("user_undo", (userId) => { - setUsers((prevUsers) => { - const newUsers = { ...prevUsers }; - if (Array.isArray(newUsers[userId])) { - newUsers[userId] = newUsers[userId].slice(0, -1); - } - if (ctx) { - drawOnUndo(ctx, savedMoves, newUsers); + if (movesToDrawLater && userIdLater && ctx) { + handleMove(movesToDrawLater, ctx); handleEnd(); + setUsers((prevUsers) => { + const newUsers = { ...prevUsers }; + newUsers[userIdLater] = [ + ...newUsers[userIdLater], movesToDrawLater as Move]; + return newUsers; + }) } - return newUsers; + }; + }, [ctx, handleEnd, setUsers, drawing]); + + useEffect(() => { + socket.on("user_undo", (userId) => { + setUsers((prevUsers) => { + const newUsers = { ...prevUsers }; + if (Array.isArray(newUsers[userId])) { + newUsers[userId] = newUsers[userId].slice(0, -1); + } + if (ctx) { + drawOnUndo(ctx, savedMoves, newUsers); + handleEnd(); + } + return newUsers; + }); }); - }); return () => { socket.off("user_undo"); }; - },[ctx, handleEnd, setUsers]); - + }, [ctx, handleEnd, setUsers]); + }; diff --git a/server/index.ts b/server/index.ts index d360cb3..c486650 100644 --- a/server/index.ts +++ b/server/index.ts @@ -1,81 +1,77 @@ - import { createServer } from "http"; -import {} from "@/common/types/global" import express from "express"; -import next, { NextApiHandler } from "next"; -import {Server} from "socket.io"; +import next from "next"; +import { Server } from "socket.io"; +import {} from "@/common/types/global"; -const port= parseInt(process.env.PORT || "3000", 10); +const port = parseInt(process.env.PORT || "3000", 10); const dev = process.env.NODE_ENV !== "production"; -const nextApp= next({ dev }); -const nextHandler= nextApp.getRequestHandler(); - -nextApp.prepare().then(async() =>{ -const app= express(); -const server= createServer(app); -const io= new Server(server); +const nextApp = next({ dev }); +const nextHandler = nextApp.getRequestHandler(); -app.get("/hello", async(_, res)=>{ - res.send("Hello ji!"); -}); +nextApp.prepare().then(async () => { + const app = express(); + const server = createServer(app); + const io = new Server(server); + app.get("/hello", async (_, res) => { + res.send("Hello ji!"); + }); - const rooms= new Map(); + const rooms = new Map(); rooms.set("global", new Map()); const addMove = (roomId: string, socketId: string, move: Move) => { - const room= rooms.get(roomId); + const room = rooms.get(roomId); - if(!room?.has(socketId)){ + if (!room?.has(socketId)) { room?.set(socketId, [move]); } room?.get(socketId)?.push(move); - }; - const undoMove= (roomId: string, socketId: string) => { + const undoMove = (roomId: string, socketId: string) => { const room = rooms.get(roomId); room?.get(socketId)?.pop(); }; -io.on("connection", (socket)=>{ - console.log("connection"); - - socket.join("global"); - rooms.get("global")?.set(socket.id, []); + io.on("connection", (socket) => { + console.log("connection"); - io.to(socket.id).emit("joined", JSON.stringify([...rooms.get("global")!])); + socket.join("global"); + rooms.get("global")?.set(socket.id, []); + io.to(socket.id).emit("joined", JSON.stringify([...rooms.get("global")!])); - const allUsers= io.sockets.adapter.rooms.get("global"); + const allUsers = io.sockets.adapter.rooms.get("global"); if (allUsers) io.to("global").emit("users_in_room", [...allUsers]); - socket.on("draw", (move)=>{ - console.log("drawing"); - addMove("global", socket.id, move); - socket.broadcast.emit("user_draw", move, socket.id); + socket.on("draw", (move) => { + console.log("drawing"); + addMove("global", socket.id, move); + socket.broadcast.emit("user_draw", move, socket.id); + }); + + socket.on("undo", () => { + console.log("undo"); + undoMove("global", socket.id); + socket.broadcast.emit("user_undo", socket.id); + }); + + socket.on("mouse_move", (x, y) => { + console.log("mouse move"); + socket.broadcast.emit("mouse_moved", x, y, socket.id); + }); + + socket.on("disconnect", () => { + console.log("disconnected"); + rooms.get("global")?.delete(socket.id); + io.to("global").emit("user_disconnected", socket.id); + }); }); - //socket.on("mouse_move", (x,y) => { - // console.log("mouse move"); - // socket.broadcast.emit("mouse_moved", x, y, socket.id); - - //}); - - socket.on("undo", ()=>{ - console.log("undo"); - undoMove("global", socket.id); - socket.broadcast.emit("user_undo", socket.id); - }); - - socket.on("disconnect", ()=>{ - console.log("disconnected"); + app.all("*", (req, res) => nextHandler(req, res)); + server.listen(port, () => { + console.log(`Server is ready on ${port}`); }); - -}); - -app.all("*", (req, res) => nextHandler(req, res)); -server.listen(port, () =>{ - console.log(`Server is ready on ${port}`); }); -}); \ No newline at end of file