Skip to content

Commit

Permalink
fix cursor functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 21, 2024
1 parent 27b9107 commit 33da425
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 113 deletions.
4 changes: 1 addition & 3 deletions modules/room/components/MousePosition.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)}
</motion.div>
);
};
};
21 changes: 11 additions & 10 deletions modules/room/components/MouseRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <UserMouse userId={userId} key={userId} />;
})}
</>
);
return (
<>
{userIds.map((userId) => (
<UserMouse userId={userId} key={userId} />
))}
</>
);
};
export default MouseRenderer;

export default MouseRenderer;
12 changes: 8 additions & 4 deletions modules/room/components/UserMouse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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(() => {
Expand All @@ -32,7 +36,7 @@ const UserMouse = ({ userId }: { userId: string }) => {

return (
<motion.div
className={`absolute top-0 left-0 text-blue-800 ${pos.x === -1 && 'hidden'}pointer-events-none`}
className={`absolute top-0 left-0 text-blue-800 ${pos.x === -1 ? 'hidden' : ''} pointer-events-none`}
animate={{ x: pos.x + x, y: pos.y + y }}
transition={{ duration: 0.3, ease: "linear" }}
>
Expand Down
86 changes: 42 additions & 44 deletions modules/room/hooks/Canvas.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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]);

};
100 changes: 48 additions & 52 deletions server/index.ts
Original file line number Diff line number Diff line change
@@ -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<ClientToServerEvents, ServerToClientEvents>(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<ClientToServerEvents, ServerToClientEvents>(server);

app.get("/hello", async (_, res) => {
res.send("Hello ji!");
});

const rooms= new Map<string, Room>();
const rooms = new Map<string, Room>();
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}`);
});
});

0 comments on commit 33da425

Please sign in to comment.