Skip to content

Commit

Permalink
add username functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 23, 2024
1 parent 8c6e7a7 commit 5ba024f
Show file tree
Hide file tree
Showing 11 changed files with 147 additions and 67 deletions.
1 change: 1 addition & 0 deletions common/recoil/room/room.atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const roomAtom = atom<ClientRoom>({
default: {
id: "",
users: new Map(),
usersMoves: new Map(),
movesWithoutUser: [],
myMoves: [],
},
Expand Down
44 changes: 25 additions & 19 deletions common/recoil/room/room.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,49 +28,55 @@ export const useSetRoomId = () => {
};

export const useSetUsers = () => {
const setUsers = useSetRecoilState(roomAtom);
const setRoom = useSetRecoilState(roomAtom);

const handleAddUser= (userId: string) => {
setUsers((prev)=> {
const users = new Map(prev.users);
users.set(userId, []);
return {...prev, users};
const handleAddUser= (userId: string, username: string) => {
setRoom((prev)=> {
const newUsers = prev.users;
const newUsersMoves = prev.usersMoves;

newUsers.set(userId, username);
newUsersMoves.set(userId, []);
return {...prev, users: newUsers, usersMoves: newUsersMoves};
});
};


const handleRemoveUser = (userId: string) => {
setUsers((prev)=> {
setRoom((prev)=> {
const newUsers = prev.users;
const userMoves= newUsers.get(userId);
newUsers.delete(userId);
const newUsersMoves = prev.usersMoves;

const userMoves= newUsersMoves.get(userId);
newUsers.delete(userId);
newUsersMoves.delete(userId);
return {
...prev,
users: newUsers,
usersMoves: newUsersMoves,
movesWithoutUser: [...prev.movesWithoutUser, ...(userMoves || [])],
};
});
};

const handleAddMoveToUser = (userId: string, moves: Move) => {
setUsers((prev)=>{
const newUsers = prev.users;
const oldMoves = prev.users.get(userId);
newUsers.set(userId, [...(oldMoves || []), moves]);
return {...prev, users: newUsers};
setRoom((prev)=>{
const newUsersMoves = prev.usersMoves;
const oldMoves = prev.usersMoves.get(userId);
newUsersMoves.set(userId, [...(oldMoves || []), moves]);
return {...prev, usersMoves: newUsersMoves};

});
};

const handleRemoveMoveFromUser = (userId: string) => {
setUsers((prev)=> {
const newUsers= prev.users;
const oldMoves= prev.users.get(userId);
setRoom((prev)=> {
const newUsersMoves= prev.usersMoves;
const oldMoves= prev.usersMoves.get(userId);
oldMoves?.pop();

newUsers.set(userId, oldMoves || []);
return {...prev, users: newUsers};
newUsersMoves.set(userId, oldMoves || []);
return {...prev, usersMoves: newUsersMoves};
});
};

Expand Down
18 changes: 12 additions & 6 deletions common/types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,38 @@ export declare global {
options: CtxOptions;
}

type Room = {users: Map<string, Move[]>; drawed: Move[]};
type Room = {usersMoves: Map<string, Move[]>;
drawed: Move[];
users: Map<string, string>;
};

interface ClientRoom{
id:string;
users: Map<string, Move[]>;
usersMoves: Map<string, Move[]>;
movesWithoutUser: Move[];
myMoves: Move[];
users: Map<string, string>;
}

interface ServerToClientEvents {
room: (room: Room, usersToParse: string)=> void;
room_exists: (exists: boolean) => void;
room: (room: Room, usersMovesToParse: string, usersToParse: string)=> void;
created: (roomId: string) => void;
joined:(roomId :string, failed?:boolean) => void;
user_draw: (move: Move, userId: string) => void;
user_undo(userId: string): void;
mouse_moved: (x:number, y:number, userId: string) => void;
new_user: (userId: string) => void;
new_user: (userId: string, username: string) => void;
user_disconnected: (userId: string) => void;
}

interface ClientToServerEvents {
check_room: (roomId: string) => void;
draw: (move: Move) => void;
mouse_move: (x:number, y:number) => void;
undo: () => void;
create_room: () => void;
join_room: (room: string) => void;
create_room: (username: string) => void;
join_room: (room: string, username: string) => void;
joined_room: () => void;
leave_room: () => void;
}
Expand Down
27 changes: 23 additions & 4 deletions modules/home/components/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { useModal } from '@/common/recoil/modal';

const Home = () => {
const [roomId, setRoomId] = useState("");

const [username, setUsername] = useState("");
const setAtomRoomId = useSetRoomId();

const router = useRouter();
Expand Down Expand Up @@ -44,12 +44,12 @@ const Home = () => {
}, [openModal, roomId, router, setAtomRoomId]);

const handleCreateRoom = () => {
socket.emit("create_room");
socket.emit("create_room", username);
};

const handleJoinRoom = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
socket.emit("join_room", roomId);
socket.emit("join_room", roomId, username);
};

return (
Expand All @@ -59,7 +59,19 @@ const Home = () => {
</h1>
<h3 className="text-2xl mt-4">Sketching and Fun for Everyone!</h3>

<form className="mt-8 flex flex-col items-center gap-4" onSubmit={handleJoinRoom}>
<div className='mt-10 flex flex-col gap-2'>
<label className='self-start font-bold leading-tight'>Enter Your Name</label>
<input
className='rounded-xl border p-5 py-1'
id='room-id'
placeholder='Username'
value={username}
onChange={(e) => setUsername(e.target.value)}
>
</input>
</div>
//recent changes
<form className=" flex flex-col items-center gap-3" onSubmit={handleJoinRoom}>
<label htmlFor="room-id" className="w-full text-center self-start text-lg font-bold leading-tight">
Enter Room ID
</label>
Expand All @@ -78,6 +90,13 @@ const Home = () => {
</button>
</form>

<div className='my-8 flex w-96 items-center gap-2'>
<div className='h-px w-full bg-zinc-200' />
<p className='text-zinc-400'>Or</p>
<div className='h-px w-full bg-zinc-200' />
</div>


<div className="mt-8 flex flex-col items-center gap-4">
<h5 className="self-start text-lg font-bold leading-tight">
Create a New Room
Expand Down
7 changes: 6 additions & 1 deletion modules/room/components/MouseRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ export const MouseRenderer = () => {
<>
{[...room.users.keys()].map((userId) => {
if (userId === socket.id) return null;
return <UserMouse userId={userId} key={userId} />
return (
<UserMouse
userId={userId}
key={userId}
username={room.users.get(userId) || "Anonymous"} />
);
})}
</>
);
Expand Down
65 changes: 65 additions & 0 deletions modules/room/components/NameInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { socket } from "@/common/lib/socket";
import { useSetRoomId } from "@/common/recoil/room";
import { useRouter } from "next/router";
import { FormEvent, useEffect, useState } from "react";



const NameInput = () => {
const setRoomId= useSetRoomId();
const [name, setName]= useState("");
const router= useRouter();
const roomId= (router.query.roomId || "").toString();

useEffect(()=> {
if(!roomId) return;
socket.emit("check_room", roomId);
socket.on("room_exists", (exists)=> {
console.log("room exists", exists);
if(!exists){
router.push("/");
}
});
return () => {
socket.off("room_exists");
};
}, [roomId, router]);

useEffect(()=> {
const handleJoined= (roomIdFromServer: string, failed?: boolean) => {
if(failed) router.push("/");
else setRoomId(roomIdFromServer);
};
socket.on("joined", handleJoined);

return () => {
socket.off("joined", handleJoined);
};

}, [router, setRoomId]);
const handleJoinRoom= (e:FormEvent<HTMLFormElement>) => {
e.preventDefault();
socket.emit("join_room", roomId, name);
};

return (
<form className="flex flex-col items-center" onSubmit={handleJoinRoom}>
<h1 className="mt-24 text-extra font-extrabold leading-tight">SketchParty</h1>
<h3 className="text-2xl">Sketching and Fun for everyone</h3>
<div className="mt-10 mb-3 flex flex-col gap-2">
<label className="self-start font-bold leading-tight">Enter Your Name</label>
<input className="rounded-xl border p-5 py-1" id="room-id" placeholder="Username" value={name} onChange={(e)=> setName(e.target.value)}></input>
</div>

<button
className="rounded-full bg-teal-500 px-8 py-2 text-white text-lg font-semibold transition-all hover:scale-105 active:scale-100 shadow-lg"
type="submit"
>
Enter Room
</button>

</form>
);
};

export default NameInput;
30 changes: 3 additions & 27 deletions modules/room/components/Room.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,18 @@
import { useEffect } from "react";

import { useRouter } from "next/router";

import { socket } from "@/common/lib/socket";
import { useRoom, useSetRoomId } from "@/common/recoil/room";
import { useRoom} from "@/common/recoil/room";

import RoomContextProvider from "../context/Room.context";
import Canvas from "./Canvas";
import { MousePosition } from "./MousePosition";
import MouseRenderer from "./MouseRenderer";
import { ToolBar } from "./toolbar/ToolBar";
import NameInput from "./NameInput";




const Room = () => {
const room = useRoom();
const setRoomId= useSetRoomId();
const router= useRouter();

useEffect(()=> {
const handleJoined = (roomIdFromServer: string, failed?:boolean) => {
if(failed) router.push("/");
else setRoomId(roomIdFromServer);
};
socket.on("joined", handleJoined);

return () => {
socket.off("joined", handleJoined);
};
}, [router, setRoomId]);

if(!room.id) {
const dynamicRoomId= router.query.roomId?.toString();
if( dynamicRoomId) socket.emit("join_room", dynamicRoomId);
return null;

}
if(!room.id) return <NameInput />

return (
<RoomContextProvider>
Expand Down
3 changes: 2 additions & 1 deletion modules/room/components/UserMouse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { motion } from "framer-motion";
import { BsCursorFill } from "react-icons/bs";

//cursor issue
const UserMouse = ({ userId }: { userId: string }) => {
const UserMouse = ({ userId, username, }: { userId: string, username: string }) => {
const boardPos = useBoardPosition();
const [x, setX] = useState(boardPos.x.get());
const [y, setY] = useState(boardPos.y.get());
Expand Down Expand Up @@ -41,6 +41,7 @@ const UserMouse = ({ userId }: { userId: string }) => {
transition={{ duration: 0.1, ease: "linear" }}
>
<BsCursorFill className="-rotate-90" />
<p className="ml-2">{username}</p>
</motion.div>
);
};
Expand Down
11 changes: 6 additions & 5 deletions modules/room/context/Room.context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,19 @@ const RoomContextProvider = ({ children }: { children: ReactChild }) => {
// socket events for user join/leave and clean up listeners
useEffect(()=> {

socket.on("room",(room, usersToParse)=> {
const users= new Map< string, Move[]>(JSON.parse(usersToParse));

socket.on("room",(room, usersMovesToParse, usersToParse)=> {
const usersMoves= new Map< string, Move[]>(JSON.parse(usersMovesToParse));
const users= new Map< string, string>(JSON.parse(usersToParse))
setRoom((prev)=>({
...prev,
users,
usersMoves,
movesWithoutUser: room.drawed,
}));
});

socket.on("new_user", (newUser)=> {
handleAddUser(newUser);
socket.on("new_user", (userId, username)=> {
handleAddUser(userId, username);
});


Expand Down
4 changes: 2 additions & 2 deletions modules/room/helpers/Canvas.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ export const handleMove = (
ctx: CanvasRenderingContext2D,
room: ClientRoom
) => {
const {users, movesWithoutUser, myMoves} = room;
const {usersMoves, movesWithoutUser, myMoves} = room;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

movesWithoutUser.forEach((move)=>{
handleMove(move,ctx);
});

users.forEach((userMoves)=>{
usersMoves.forEach((userMoves)=>{
userMoves.forEach((move)=> handleMove(move,ctx));
});

Expand Down
4 changes: 2 additions & 2 deletions modules/room/hooks/useDraw.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useOptions } from "@/common/recoil/options";
import { useOptionsValue } from "@/common/recoil/options";
import { useUsers } from "@/common/recoil/users";
import { useState, useEffect, useCallback} from "react";
import { useBoardPosition } from "./useBoardPosition";
Expand All @@ -23,7 +23,7 @@ export const useDraw = (
const movedX = boardPosition.x;
const movedY = boardPosition.y;

const options = useOptions();
const options = useOptionsValue();

useEffect(() => {
if (ctx) {
Expand Down

0 comments on commit 5ba024f

Please sign in to comment.