Skip to content

Commit 3d991ab

Browse files
committed
stage: Beefore optimizations
1 parent 701cab8 commit 3d991ab

File tree

4 files changed

+117
-93
lines changed

4 files changed

+117
-93
lines changed

apps/collabydraw/components/canvas/CanvasSheet.tsx

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
5454
);
5555

5656
useEffect(() => {
57-
console.log('E2')
57+
// console.log('E2')
5858
paramsRef.current = { roomId, roomName, userId, userName };
5959
}, [roomId, roomName, userId, userName]);
6060

@@ -73,7 +73,7 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
7373
});
7474

7575
useEffect(() => {
76-
console.log('E4')
76+
// console.log('E4')
7777
const handleResize = () => {
7878
if (canvasRef.current && gameRef.current) {
7979
const canvas = canvasRef.current;
@@ -88,58 +88,58 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
8888
}, [gameRef]);
8989

9090
useEffect(() => {
91-
console.log('E6')
91+
// console.log('E6')
9292
strokeEdgeRef.current = strokeEdge;
9393
gameRef?.current?.setStrokeEdge(strokeEdge);
9494
}, [strokeEdge, gameRef]);
9595

9696
useEffect(() => {
97-
console.log('E7')
97+
// console.log('E7')
9898
strokeStyleRef.current = strokeStyle;
9999
gameRef?.current?.setStrokeStyle(strokeStyle);
100100
}, [strokeStyle, gameRef]);
101101

102102
useEffect(() => {
103-
console.log('E8')
103+
// console.log('E8')
104104
activeToolRef.current = activeTool;
105105
gameRef?.current?.setTool(activeTool);
106106
}, [activeTool, gameRef]);
107107

108108
useEffect(() => {
109-
console.log('E9')
109+
// console.log('E9')
110110
strokeWidthRef.current = strokeWidth;
111111
gameRef?.current?.setStrokeWidth(strokeWidth);
112112
}, [strokeWidth, gameRef]);
113113

114114
useEffect(() => {
115-
console.log('E10')
115+
// console.log('E10')
116116
strokeFillRef.current = strokeFill;
117117
gameRef?.current?.setStrokeFill(strokeFill);
118118
}, [strokeFill, gameRef]);
119119

120120
useEffect(() => {
121-
console.log('E11')
121+
// console.log('E11')
122122
bgFillRef.current = bgFill;
123123
gameRef?.current?.setBgFill(bgFill);
124124
}, [bgFill, gameRef]);
125125

126126
useEffect(() => {
127-
console.log('E12')
127+
// console.log('E12')
128128
if (gameRef.current && canvasColorRef.current !== canvasColor) {
129129
canvasColorRef.current = canvasColor;
130130
gameRef.current.setCanvasBgColor(canvasColor);
131131
}
132132
}, [canvasColor, gameRef]);
133133

134134
useEffect(() => {
135-
console.log('E13')
135+
// console.log('E13')
136136
if (gameRef.current) {
137137
gameRef.current.setScale(scale);
138138
}
139139
}, [scale, gameRef]);
140140

141141
useEffect(() => {
142-
console.log('E14')
142+
// console.log('E14')
143143
const handleKeyDown = (e: KeyboardEvent) => {
144144
switch (e.key) {
145145
case "1":
@@ -180,13 +180,7 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
180180
}, [isConnected, sendMessage]);
181181

182182
useEffect(() => {
183-
if (game && existingShapes.length >= 0) {
184-
game.updateShapes(existingShapes);
185-
}
186-
}, [game, existingShapes]);
187-
188-
useEffect(() => {
189-
console.log('E16')
183+
// console.log('E16')
190184
if (!canvasRef.current || !isConnected) return;
191185
console.log('Initializing game with valid socket');
192186
const game = new Game(
@@ -212,7 +206,11 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
212206
}, [handleSendDrawing, isConnected]);
213207

214208
useEffect(() => {
215-
console.log('E17')
209+
console.log('isConnected = ', isConnected);
210+
}, [isConnected])
211+
212+
useEffect(() => {
213+
// console.log('E17')
216214
if (activeTool === "grab") {
217215
const handleGrab = () => {
218216
setGrabbing((prev) => !prev)
@@ -236,8 +234,18 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
236234
console.log(`looping messages ${index}= `, message)
237235
try {
238236
if (message.type === WS_DATA_TYPE.DRAW) {
239-
setExistingShapes((prevShapes) => [...prevShapes, message.message!]);
240-
} else if (message.type === WS_DATA_TYPE.ERASER) {
237+
setExistingShapes((prevShapes) => {
238+
const alreadyExists = prevShapes.some(s => s.id === message.id);
239+
console.log('alreadyExists = ', alreadyExists)
240+
if (alreadyExists) return prevShapes;
241+
return [...prevShapes, message.message!];
242+
});
243+
} else if (message.type === WS_DATA_TYPE.UPDATE) {
244+
setExistingShapes((prevShapes) =>
245+
prevShapes.map((shape) =>
246+
shape.id === message.id ? { ...shape, ...message.message } : shape));
247+
}
248+
else if (message.type === WS_DATA_TYPE.ERASER) {
241249
setExistingShapes((prevShapes) =>
242250
prevShapes.filter((s) => s.id !== message.id)
243251
);
@@ -252,14 +260,21 @@ export default function CanvasSheet({ roomName, roomId, userId, userName, token
252260
}
253261
}, [messages]);
254262

263+
useEffect(() => {
264+
if (game && existingShapes.length >= 0) {
265+
game.updateShapes(existingShapes);
266+
console.log('Called game.updateShapes(existingShapes);')
267+
}
268+
}, [game, existingShapes]);
269+
255270
const toggleSidebar = useCallback(() => {
256-
console.log('E19')
271+
// console.log('E19')
257272
setSidebarOpen(prev => !prev);
258273
}, []);
259274

260-
useEffect(() => {
261-
console.log('participants = ', participants)
262-
}, [participants])
275+
// useEffect(() => {
276+
// console.log('participants = ', participants)
277+
// }, [participants])
263278

264279
if (isLoading) {
265280
return <ScreenLoading />

apps/collabydraw/draw/Game.ts

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
} from "@/types/canvas";
99
import { SelectionManager } from "./SelectionManager";
1010
import { v4 as uuidv4 } from "uuid";
11-
import { RoomParticipants, WS_DATA_TYPE } from "@repo/common/types";
11+
import { WS_DATA_TYPE } from "@repo/common/types";
1212

1313
const CORNER_RADIUS_FACTOR = 20;
1414
const RECT_CORNER_RADIUS_FACTOR = CORNER_RADIUS_FACTOR;
@@ -55,9 +55,6 @@ export class Game {
5555
private selectedShape: Shape | null = null;
5656
private selectionManager: SelectionManager;
5757

58-
private participants: RoomParticipants[] = [];
59-
private onParticipantsChange?: (participants: RoomParticipants[]) => void;
60-
6158
constructor(
6259
canvas: HTMLCanvasElement,
6360
roomId: string | null,
@@ -115,6 +112,7 @@ export class Game {
115112
if (shape && shape.message) {
116113
const parsedShapeMessage = JSON.parse(shape.message);
117114
this.existingShape.push(parsedShapeMessage);
115+
console.log("init(): Pushing shapes from getRoomResult");
118116
} else {
119117
console.warn(`Shape ${index} has no message property`);
120118
}
@@ -291,7 +289,7 @@ export class Game {
291289
this.activeTool !== "eraser" &&
292290
this.activeTool !== "line" &&
293291
this.activeTool !== "arrow"
294-
)
292+
) {
295293
if (this.activeTool === "selection") {
296294
if (
297295
this.selectionManager.isDraggingShape() ||
@@ -302,10 +300,8 @@ export class Game {
302300
const index = this.existingShape.findIndex(
303301
(shape) => shape.id === selectedShape.id
304302
);
303+
this.existingShape[index] = selectedShape;
305304
if (index !== -1) {
306-
this.existingShape[index] = selectedShape;
307-
this.clearCanvas();
308-
309305
if (this.isStandalone) {
310306
localStorage.setItem(
311307
LOCALSTORAGE_CANVAS_KEY,
@@ -323,20 +319,19 @@ export class Game {
323319
}
324320
}
325321
}
322+
this.selectionManager.stopDragging();
323+
this.selectionManager.stopResizing();
324+
return;
326325
}
327-
this.selectionManager.stopDragging();
328-
this.selectionManager.stopResizing();
329-
return;
330326
}
331-
327+
}
332328
this.clicked = false;
333329

334330
if (this.selectedShape) {
335331
localStorage.setItem(
336332
LOCALSTORAGE_CANVAS_KEY,
337333
JSON.stringify(this.existingShape)
338334
);
339-
this.clearCanvas();
340335
}
341336

342337
const { x, y } = this.transformPanScale(e.clientX, e.clientY);
@@ -445,10 +440,9 @@ export class Game {
445440
return;
446441
}
447442

448-
this.existingShape.push(shape);
449-
450443
if (this.isStandalone) {
451444
try {
445+
this.existingShape.push(shape);
452446
localStorage.setItem(
453447
LOCALSTORAGE_CANVAS_KEY,
454448
JSON.stringify(this.existingShape)
@@ -466,6 +460,7 @@ export class Game {
466460
})
467461
);
468462
}
463+
this.clearCanvas();
469464
};
470465

471466
mouseWheelHandler = (e: WheelEvent) => {

apps/collabydraw/hooks/useWebSocket.tsx

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,26 +38,26 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
3838

3939
try {
4040
const wsUrl = `${WS_URL}?token=${encodeURIComponent(paramsRef.current.token)}`;
41-
console.log('Connecting to WebSocket...');
41+
// console.log('Connecting to WebSocket...');
4242

4343
const ws = new WebSocket(wsUrl);
4444

4545
const connectionTimeout = setTimeout(() => {
4646
if (ws.readyState !== WebSocket.OPEN) {
47-
console.log('WebSocket connection timeout, closing...');
47+
// console.log('WebSocket connection timeout, closing...');
4848
ws.close();
4949
}
5050
}, 5000);
5151

5252
const handleOpen = () => {
5353
clearTimeout(connectionTimeout);
54-
console.log('WebSocket connected successfully');
54+
// console.log('WebSocket connected successfully');
5555
setIsConnected(true);
5656
reconnectAttemptsRef.current = 0;
5757
hasJoinedRoomRef.current = false;
5858
setTimeout(() => {
5959
const { roomId, roomName, userId, userName } = paramsRef.current;
60-
console.log(`Joining room ${roomId} as ${userName}`);
60+
// console.log(`Joining room ${roomId} as ${userName}`);
6161

6262
ws.send(JSON.stringify({
6363
type: WS_DATA_TYPE.JOIN,
@@ -74,7 +74,7 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
7474
const handleMessage = (event: MessageEvent) => {
7575
try {
7676
const data: WebSocketMessage = JSON.parse(event.data);
77-
console.log('Received WebSocket message:', data);
77+
console.log('Received WS Message:', data);
7878

7979
switch (data.type) {
8080
case WS_DATA_TYPE.USER_JOINED:
@@ -87,8 +87,8 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
8787
const exists = prev.some(p => p.userId === data.userId);
8888
if (!exists) {
8989
return [...prev, {
90-
userId: data.userId!,
91-
userName: data.userName!
90+
userId: data.userId,
91+
userName: data.userName || paramsRef.current.userName
9292
}];
9393
}
9494
return prev;
@@ -104,16 +104,28 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
104104
break;
105105

106106
case WS_DATA_TYPE.DRAW:
107+
if (data.message) {
108+
const parsedMessage = JSON.parse(data.message);
109+
setMessages(prev => [...prev, {
110+
type: data.type,
111+
userId: data.userId || paramsRef.current.userId,
112+
userName: data.userName || paramsRef.current.userName,
113+
message: parsedMessage,
114+
timestamp: data.timestamp || new Date().toISOString()
115+
}]);
116+
}
117+
break;
118+
107119
case WS_DATA_TYPE.UPDATE:
108120
if (data.message) {
109121
const parsedMessage = JSON.parse(data.message);
110-
const timestamp = data.timestamp || new Date().toISOString();
111122
setMessages(prev => [...prev, {
112123
type: data.type,
113-
userId: data.userId! || paramsRef.current.userId,
114-
userName: data.userName! || paramsRef.current.userName,
124+
id: data.id,
115125
message: parsedMessage,
116-
timestamp
126+
userId: data.userId || paramsRef.current.userId,
127+
userName: data.userName || paramsRef.current.userName,
128+
timestamp: data.timestamp || new Date().toISOString()
117129
}]);
118130
}
119131
break;
@@ -138,10 +150,10 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
138150
const handleClose = (event: CloseEvent) => {
139151
clearTimeout(connectionTimeout);
140152
setIsConnected(false);
141-
console.log(`WebSocket closed with code ${event.code}: ${event.reason}`);
153+
// console.log(`WebSocket closed with code ${event.code}: ${event.reason}`);
142154
if (event.code !== 1000 && reconnectAttemptsRef.current < MAX_RECONNECT_ATTEMPTS) {
143155
const delay = Math.min(1000 * 2 ** reconnectAttemptsRef.current, 30000);
144-
console.log(`Reconnecting in ${delay}ms (attempt ${reconnectAttemptsRef.current + 1})`);
156+
// console.log(`Reconnecting in ${delay}ms (attempt ${reconnectAttemptsRef.current + 1})`);
145157

146158
reconnectTimeoutRef.current = setTimeout(() => {
147159
reconnectAttemptsRef.current += 1;
@@ -183,7 +195,7 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
183195
if (socketRef.current) {
184196
try {
185197
if (socketRef.current.readyState === WebSocket.OPEN && hasJoinedRoomRef.current) {
186-
console.log(`Leaving room ${paramsRef.current.roomId}`);
198+
// console.log(`Leaving room ${paramsRef.current.roomId}`);
187199
socketRef.current.send(JSON.stringify({
188200
type: WS_DATA_TYPE.LEAVE,
189201
roomId: paramsRef.current.roomId
@@ -202,7 +214,7 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
202214
console.warn('Cannot send empty message');
203215
return;
204216
}
205-
console.log("sendMessage content = ", JSON.parse(content))
217+
// console.log("Sending WS Content = ", JSON.parse(content))
206218
const parsedContent = JSON.parse(content);
207219
if (socketRef.current?.readyState === WebSocket.OPEN) {
208220
const { roomName, userId, userName } = paramsRef.current;

0 commit comments

Comments
 (0)