Skip to content

Commit

Permalink
add userefs, download functionality not working
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 28, 2024
1 parent a95cea1 commit 48d328b
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 57 deletions.
5 changes: 5 additions & 0 deletions modules/home/components/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ const Home = () => {
};
}, [openModal, roomId, router, setAtomRoomId]);

useEffect(()=> {
socket.emit("leave_room");
setAtomRoomId("");
},[setAtomRoomId]);

const handleCreateRoom = () => {
socket.emit("create_room", username);
};
Expand Down
5 changes: 2 additions & 3 deletions modules/room/components/Room.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ import Chat from "./chat/Chat";
const Room = () => {
const room = useRoom();

const undoRef= useRef<HTMLButtonElement>(null);
if(!room.id) return <NameInput />;

return (
<RoomContextProvider>
<div className="relative h-full w-full overflow-hidden">
<UsersList />
<ToolBar undoRef={undoRef}/>
<Canvas undoRef={undoRef}/>
<ToolBar />
<Canvas />
<MousePosition />
<MouseRenderer />
<Chat />
Expand Down
13 changes: 6 additions & 7 deletions modules/room/components/board/Background.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { useEffect, useRef } from "react";
import { RefObject, useEffect } from "react";
import { useBoardPosition } from "../../hooks/useBoardPosition";
import {motion} from "framer-motion";
import { CANVAS_SIZE } from "@/common/constants/canvasSize";

const Background = () => {
const Background = ({bgRef}: {bgRef: RefObject<HTMLCanvasElement>}) => {
const {x,y} = useBoardPosition();
const ref= useRef<HTMLCanvasElement>(null);


useEffect(()=> {
const ctx= ref.current?.getContext("2d");
const ctx=bgRef.current?.getContext("2d");

if(ctx){
ctx.fillStyle="#fff";
Expand All @@ -30,10 +29,10 @@ const Background = () => {
ctx.stroke();
}
}
},[]);
},[bgRef]);
return (
<motion.canvas
ref={ref}
ref={bgRef}
width={CANVAS_SIZE.width}
height={CANVAS_SIZE.height}
className="absolute top-0 bg-zinc-100"
Expand Down
56 changes: 23 additions & 33 deletions modules/room/components/board/Canvas.tsx
Original file line number Diff line number Diff line change
@@ -1,62 +1,57 @@
import { CANVAS_SIZE } from "@/common/constants/canvasSize";
import { useViewportSize } from "@/common/hooks/useViewportSize";
import { useMotionValue, motion } from "framer-motion";
import { useRef, useState, useEffect, RefObject } from "react";
import { useRef, useState, useEffect, useCallback } from "react";
import { useKeyPressEvent } from "react-use";
import { useDraw } from "../../hooks/useDraw";
import { useSocketDraw } from "../../hooks/useSocketDraw";
import { socket } from "@/common/lib/socket";
import Minimap from "./Minimap";
import room, { useRoom } from "@/common/recoil/room";
import { useRoom } from "@/common/recoil/room";
import { drawAllMoves } from "../../helpers/Canvas.helpers";
import { useBoardPosition } from "../../hooks/useBoardPosition";
import Background from "./Background";
import { useOptionsValue } from "@/common/recoil/options";
import { useRefs } from "../../hooks/useRefs";


const Canvas = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
const room= useRoom();
const options= useOptionsValue();
const canvasRef = useRef<HTMLCanvasElement>(null);
const Canvas = () => {
const room = useRoom();
const options = useOptionsValue();
const { canvasRef, bgRef, undoRef } = useRefs(); // Call the hook as a function
const smallCanvasRef = useRef<HTMLCanvasElement>(null);

const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
const [dragging, setDragging] = useState(false);
const [, setMovedMiniMap] = useState(false);

const { width, height } = useViewportSize();
const {x,y} = useBoardPosition();
const { x, y } = useBoardPosition();

useKeyPressEvent("Control", (e) => {
if (e.ctrlKey && !dragging) {
setDragging(true);
}
});


const copyCanvasToSmall = () => {
const copyCanvasToSmall = useCallback(() => {
if (canvasRef.current && smallCanvasRef.current) {
const smallCtx = smallCanvasRef.current.getContext("2d");
if (smallCtx){
if (smallCtx) {
smallCtx.clearRect(0, 0, CANVAS_SIZE.width, CANVAS_SIZE.height);
smallCtx.drawImage(
smallCtx.drawImage(
canvasRef.current,
0,
0,
CANVAS_SIZE.width,
CANVAS_SIZE.height
);
}

}
};
}, [canvasRef, smallCanvasRef]);

const { handleEndDrawing, handleDraw, handleStartDrawing, drawing, handleUndo } = useDraw(
ctx,
dragging
);
const { handleEndDrawing, handleDraw, handleStartDrawing, drawing, handleUndo } = useDraw(ctx, dragging);

useSocketDraw(ctx,drawing);
useSocketDraw(ctx, drawing);

useEffect(() => {
const newCtx = canvasRef.current?.getContext("2d");
Expand All @@ -69,27 +64,26 @@ const Canvas = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
}
window.addEventListener("keyup", handleKeyUp);

const undoBtn= undoRef.current;
const undoBtn = undoRef.current;
undoBtn?.addEventListener("click", handleUndo);

return () => {
window.removeEventListener("keyup", handleKeyUp);
undoBtn?.removeEventListener("click", handleUndo);
}
}, [dragging, handleUndo, undoRef]);
}, [dragging, handleUndo, undoRef, canvasRef]);

useEffect(()=> {
if(ctx) socket.emit("joined_room");
},[ctx]);
useEffect(() => {
if (ctx) socket.emit("joined_room");
}, [ctx]);

useEffect(()=> {
if(ctx){
useEffect(() => {
if (ctx) {
drawAllMoves(ctx, room, options);
copyCanvasToSmall();
};
}
}, [ctx, room, options]);


return (
<div className="relative h-full w-full overflow-hidden">
<motion.canvas
Expand Down Expand Up @@ -137,7 +131,7 @@ const Canvas = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
);
}}
/>
<Background/>
<Background bgRef={bgRef} />
<Minimap
ref={smallCanvasRef}
dragging={dragging}
Expand All @@ -148,7 +142,3 @@ const Canvas = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
};

export default Canvas;
function copyCanvasToSmall() {
throw new Error("Function not implemented.");
}

24 changes: 23 additions & 1 deletion modules/room/components/toolbar/ToolBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,29 @@ import { BsFillChatFill, BsFillImageFill, BsThreeDots } from "react-icons/bs";
import { HiOutlineDownload } from "react-icons/hi";
import { FaUndo } from "react-icons/fa";
import ShapeSelector from "./ShapeSelector";
import { useRefs } from "../../hooks/useRefs";
import { CANVAS_SIZE } from "@/common/constants/canvasSize";

export const ToolBar = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
export const ToolBar = ( ) => {
const {canvasRef, bgRef, undoRef}= useRefs();
const handleDownload= ()=> {
const canvas= document.createElement('canvas');
canvas.width= CANVAS_SIZE.width;
canvas.height= CANVAS_SIZE.height;

const tempCtx= canvas.getContext('2d');

if(tempCtx && canvasRef.current && bgRef.current){
tempCtx.drawImage(bgRef.current, 0, 0);
tempCtx.drawImage(canvasRef.current, 0, 0);
}

const link= document.createElement('a');
link.href= canvas.toDataURL("image/png");
link.download="canvas.png";
link.click();

};
return (
<div className="absolute left-10 top-[50%] z-50 flex flex-col items-center rounded-lg gap-5 p-5 bg-zinc-900 text-white"
style={{
Expand All @@ -28,6 +49,7 @@ export const ToolBar = ({undoRef}: {undoRef: RefObject<HTMLButtonElement>}) => {
<button className="text-xl">
<BsThreeDots />
</button>
<button className="text-xl" onClick={handleDownload}></button>
<button className="text-xl">
<HiOutlineDownload />
</button>
Expand Down
10 changes: 8 additions & 2 deletions modules/room/context/Room.context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ import { socket } from "@/common/lib/socket";
import { useSetRoom, useSetUsers } from "@/common/recoil/room/room.hooks";
import usersAtom, { useUserIds } from "@/common/recoil/users";
import { MotionValue, useMotionValue } from "framer-motion";
import { createContext, ReactChild, useEffect } from "react";
import { createContext, ReactChild, RefObject, useEffect, useRef } from "react";
import { useSet } from "react-use";
import { useSetRecoilState } from "recoil";

//creating context for x & y coordinates
export const roomContext = createContext<{
x: MotionValue<number>;
y: MotionValue<number>;
undoRef: RefObject<HTMLButtonElement>;
canvasRef: RefObject<HTMLCanvasElement>;
bgRef: RefObject<HTMLCanvasElement>;
}>(null!);

const RoomContextProvider = ({ children }: { children: ReactChild }) => {
Expand All @@ -19,6 +22,9 @@ const RoomContextProvider = ({ children }: { children: ReactChild }) => {
const {handleAddUser, handleRemoveUser} = useSetUsers();
const x = useMotionValue(0);
const y = useMotionValue(0);
const undoRef = useRef<HTMLButtonElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const bgRef = useRef<HTMLCanvasElement>(null);

// socket events for user join/leave and clean up listeners
useEffect(()=> {
Expand Down Expand Up @@ -64,7 +70,7 @@ const RoomContextProvider = ({ children }: { children: ReactChild }) => {
}, [handleAddUser, handleRemoveUser, setRoom]);
//motion values to context consumers
return (
<roomContext.Provider value={{ x, y }}>
<roomContext.Provider value={{ x, y, bgRef, undoRef, canvasRef}}>
{children}
</roomContext.Provider>
);
Expand Down
12 changes: 12 additions & 0 deletions modules/room/hooks/useRefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useContext } from "react";
import { roomContext } from "../context/Room.context";

export const useRefs= ()=> {
const {undoRef, bgRef, canvasRef} = useContext(roomContext);

return{
undoRef,
bgRef,
canvasRef,
};
}
28 changes: 17 additions & 11 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import express from "express";
import next from "next";
import { Server } from "socket.io";
import {} from "@/common/types/global";
import { socket } from "@/common/lib/socket";

const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
Expand Down Expand Up @@ -35,17 +36,6 @@ nextApp.prepare().then(async () => {
room?.usersMoves.get(socketId)?.pop();
};

const leaveRoom = (roomId: string, socketId: string) => {
const room= rooms.get(roomId);

if(!room) return;

const userMoves= room?.usersMoves.get(socketId)!;
room?.drawed.push(...userMoves);
room?.users.delete(socketId);

console.log("user left room");
};

io.on("connection", (socket) => {
//get the room id the socket is currently in, excluding its own id
Expand All @@ -54,6 +44,22 @@ nextApp.prepare().then(async () => {
if(!joinedRoom) return socket.id;
return joinedRoom;
}
const leaveRoom = (roomId: string, socketId: string) => {
const room= rooms.get(roomId);

if(!room) return;

const userMoves= room.usersMoves.get(socketId)!;

if(userMoves) room.drawed.push(...userMoves);

room.users.delete(socketId);
socket.leave(roomId);

console.log("user left room");
};


console.log("connection");

socket.on("create_room", (username) => {
Expand Down

0 comments on commit 48d328b

Please sign in to comment.