Skip to content

Commit d02eac5

Browse files
committed
fixing(websocket): Hookyfying Inprogress
1 parent 8dd9abd commit d02eac5

File tree

14 files changed

+617
-198
lines changed

14 files changed

+617
-198
lines changed

apps/collabydraw/actions/canvas.ts

Lines changed: 0 additions & 7 deletions
This file was deleted.

apps/collabydraw/actions/room.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,15 @@ export async function getRoom(data: { roomName: string }) {
8989

9090
const room = await client.room.findUnique({
9191
where: { slug: validatedRoomName.roomName },
92-
include: { Chat: true },
92+
include: { Shape: true },
9393
});
9494

9595
if (!room) {
9696
return { success: false, error: "Room not found" };
9797
}
9898

99+
console.log("room = ", room);
100+
99101
const session = await getServerSession(authOptions);
100102
const cookieToken = session?.accessToken;
101103

@@ -151,7 +153,7 @@ export async function deleteRoom(data: { roomName: string }) {
151153
};
152154
}
153155

154-
await client.chat.deleteMany({
156+
await client.shape.deleteMany({
155157
where: { roomId: room.id },
156158
});
157159

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { JoinRoomSchema } from "@repo/common/types";
66
import { getServerSession } from "next-auth";
77
import { authOptions } from "@/utils/auth";
88

9-
export async function getChats(data: { roomName: string }) {
9+
export async function getShapes(data: { roomName: string }) {
1010
try {
1111
const validatedRoomName = JoinRoomSchema.parse(data);
1212

@@ -18,15 +18,15 @@ export async function getChats(data: { roomName: string }) {
1818
return { success: false, error: "Room not found" };
1919
}
2020

21-
const chats = await client.chat.findMany({
21+
const shapesResponse = await client.shape.findMany({
2222
where: { roomId: room.id },
2323
});
2424

25-
if (!chats.length) {
25+
if (!shapesResponse.length) {
2626
return { success: true, shapes: [] };
2727
}
2828

29-
const shapes = chats.map((x: { message: string }) => {
29+
const shapes = shapesResponse.map((x: { message: string }) => {
3030
const messageData = JSON.parse(x.message);
3131
return messageData.shape;
3232
});
@@ -36,12 +36,12 @@ export async function getChats(data: { roomName: string }) {
3636
if (error instanceof z.ZodError) {
3737
return { success: false, error: "Invalid room code format" };
3838
}
39-
console.error("Failed to get chats:", error);
40-
return { success: false, error: "Failed to get chats" };
39+
console.error("Failed to get shapes:", error);
40+
return { success: false, error: "Failed to get shapes" };
4141
}
4242
}
4343

44-
export async function clearAllChats(data: { roomName: string }) {
44+
export async function clearAllShapes(data: { roomName: string }) {
4545
try {
4646
const session = await getServerSession(authOptions);
4747

@@ -68,7 +68,7 @@ export async function clearAllChats(data: { roomName: string }) {
6868
};
6969
}
7070

71-
const result = await client.chat.deleteMany({
71+
const result = await client.shape.deleteMany({
7272
where: { roomId: room.id },
7373
});
7474

@@ -80,7 +80,7 @@ export async function clearAllChats(data: { roomName: string }) {
8080
if (error instanceof z.ZodError) {
8181
return { success: false, error: "Invalid room code format" };
8282
}
83-
console.error("Failed to clear chats:", error);
84-
return { success: false, error: "Failed to clear chats" };
83+
console.error("Failed to clear shapes:", error);
84+
return { success: false, error: "Failed to clear shapes" };
8585
}
8686
}

apps/collabydraw/app/(canvas)/canvas/[roomName]/page.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export default async function CanvasPage({ params }: { params: Promise<{ roomNam
2929
roomName={room.slug}
3030
userId={user.id}
3131
userName={user.name || 'User-' + user.id}
32+
token={session.accessToken}
3233
/>
3334
)
3435
}

apps/collabydraw/components/MainMenuStack.tsx

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import { ColorPicker } from "@/components/color-picker"
2626
import { ConfirmDialog } from "./confirm-dialog"
2727
import { cn } from "@/lib/utils"
2828
import { useTheme } from "next-themes"
29-
import { clearAllChats } from "@/actions/chat"
3029
import { signOut, useSession } from "next-auth/react"
3130
import { redirect, usePathname } from "next/navigation"
3231
import Link from "next/link"
@@ -85,10 +84,8 @@ export function MainMenuStack({ isOpen, onClose, canvasColor, setCanvasColor, is
8584
title="Clear canvas"
8685
description="This will clear the whole canvas. Are you sure?"
8786
onClearCanvas={isStandalone ? onClearCanvas : undefined}
88-
onConfirm={!isStandalone ? () => clearAllChats({ roomName: roomName! }) : undefined}
8987
variant="destructive"
9088
/>
91-
9289
<section data-sidebar className={cn("transition-transform duration-300 ease-in-out z-20", isMobile ? "" : "absolute top-full mt-2")}>
9390
<div className={cn("flex flex-col", isMobile ? "" : "h-[calc(100vh-150px)] Island rounded-lg")}>
9491
<div className={cn("py-1", isMobile ? "" : "flex-1 overflow-auto py-1 custom-scrollbar")}>

apps/collabydraw/components/canvas/CanvasSheet.tsx

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import ScreenLoading from "../ScreenLoading";
1616
import CollaborationStart from "../CollaborationStartBtn";
1717
import { cn } from "@/lib/utils";
1818

19-
export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName: string; roomId: string; userId: string; userName: string; }) {
19+
export function CanvasSheet({ roomName, roomId, userId, userName, token }: { roomName: string; roomId: string; userId: string; userName: string; token: string }) {
2020
const { theme } = useTheme()
2121
const canvasRef = useRef<HTMLCanvasElement>(null);
2222
const [game, setGame] = useState<Game>();
@@ -40,11 +40,12 @@ export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName:
4040
const [canvasColor, setCanvasColor] = useState<string>(canvasBgLight[0]);
4141
const canvasColorRef = useRef(canvasColor);
4242

43-
const { isConnected, messages, sendMessage, participants } = useWebSocket(
43+
const { isConnected, messages, participants, sendDrawingData } = useWebSocket(
4444
roomId,
4545
roomName,
4646
userId,
47-
userName
47+
userName,
48+
token
4849
);
4950

5051
const { matches, isLoading } = useMediaQuery('md');
@@ -76,7 +77,7 @@ export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName:
7677
try {
7778
messages.forEach((message) => {
7879
try {
79-
const data = JSON.parse(message.content);
80+
const data = JSON.parse(message.message);
8081
console.log('ws msg data = ', data)
8182
if (data.type === "draw") {
8283
const shape = JSON.parse(data.data).shape;
@@ -97,14 +98,6 @@ export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName:
9798
}
9899
}, [messages]);
99100

100-
useEffect(() => {
101-
try {
102-
console.log('participants = ', participants)
103-
} catch (e) {
104-
console.error("Error processing messages:", e);
105-
}
106-
}, [participants]);
107-
108101
useEffect(() => {
109102
game?.setTool(activeTool)
110103
game?.setStrokeWidth(strokeWidth)
@@ -197,11 +190,27 @@ export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName:
197190
};
198191
}, [setActiveTool]);
199192

200-
const handleSendDrawing = useCallback((msgData: string) => {
193+
const handleSendDrawing = useCallback((drawingData: string) => {
201194
if (isConnected) {
202-
sendMessage(msgData);
195+
sendDrawingData(JSON.stringify(drawingData));
196+
203197
}
204-
}, [isConnected, sendMessage]);
198+
}, [isConnected, sendDrawingData]);
199+
200+
// const handleEraserComplete = useCallback((eraserData: string) => {
201+
// if (isConnected) {
202+
// sendEraserData(JSON.stringify(eraserData));
203+
204+
// }
205+
// }, [isConnected, sendEraserData]);
206+
207+
useEffect(() => {
208+
try {
209+
console.log('participants = ', participants)
210+
} catch (e) {
211+
console.error("Error processing messages:", e);
212+
}
213+
}, [participants]);
205214

206215
useEffect(() => {
207216
if (canvasRef.current) {

apps/collabydraw/draw/Game.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
StrokeStyle,
77
ToolType,
88
} from "@/types/canvas";
9-
import { RoughGenerator } from "roughjs/bin/generator";
109
import { SelectionManager } from "./SelectionManager";
1110
import { v4 as uuidv4 } from "uuid";
1211

@@ -33,7 +32,7 @@ export class Game {
3332
private ctx: CanvasRenderingContext2D;
3433
private roomId: string | null;
3534
private canvasBgColor: string;
36-
private sendMessage: ((data: string) => void) | null;
35+
private handleSendDrawing: ((data: string) => void) | null;
3736
private existingShape: Shape[];
3837
private clicked: boolean;
3938
private roomName: string | null;
@@ -51,7 +50,6 @@ export class Game {
5150
private strokeEdge: StrokeEdge = "round";
5251
private strokeStyle: StrokeStyle = "solid";
5352
private isStandalone: boolean = false;
54-
private static rg = new RoughGenerator();
5553

5654
private selectedShape: Shape | null = null;
5755
private selectionManager: SelectionManager;
@@ -60,7 +58,7 @@ export class Game {
6058
canvas: HTMLCanvasElement,
6159
roomId: string | null,
6260
canvasBgColor: string,
63-
sendMessage: ((data: string) => void) | null,
61+
handleSendDrawing: ((data: string) => void) | null,
6462
roomName: string | null,
6563
onScaleChangeCallback: (scale: number) => void,
6664
initialShapes: Shape[] = [],
@@ -70,7 +68,7 @@ export class Game {
7068
this.ctx = canvas.getContext("2d")!;
7169
this.canvasBgColor = canvasBgColor;
7270
this.roomId = roomId;
73-
this.sendMessage = sendMessage;
71+
this.handleSendDrawing = handleSendDrawing;
7472
this.clicked = false;
7573
this.existingShape = [...initialShapes];
7674
this.canvas.width = document.body.clientWidth;
@@ -106,15 +104,23 @@ export class Game {
106104
} else if (!this.isStandalone && this.roomName) {
107105
try {
108106
const getRoomResult = await getRoom({ roomName: this.roomName });
109-
if (getRoomResult?.success && getRoomResult.room?.Chat) {
107+
if (getRoomResult?.success && getRoomResult.room?.Shape) {
110108
// eslint-disable-next-line @typescript-eslint/no-explicit-any
111-
getRoomResult.room.Chat.forEach((shape: any) => {
109+
getRoomResult.room.Shape.forEach((shape: any, index: number) => {
112110
try {
113-
const parsedShapes = JSON.parse(shape.message);
114-
const parsedShapeData = JSON.parse(parsedShapes.data);
115-
this.existingShape.push(parsedShapeData.shape);
111+
console.log(`Parsing shape ${index}:`, shape);
112+
if (shape && shape.message) {
113+
const parsedShapes = JSON.parse(shape.message);
114+
console.log("parsedShapes = ", parsedShapes);
115+
// console.log("parsedShapes.data = ", parsedShapes.data);
116+
const parsedShapeData = JSON.parse(parsedShapes.data);
117+
console.log("parsedShapeData = ", parsedShapeData);
118+
this.existingShape.push(parsedShapeData.shape);
119+
} else {
120+
console.warn(`Shape ${index} has no message property`);
121+
}
116122
} catch (e) {
117-
console.error("Error parsing shape data:", e);
123+
console.error(`Error parsing shape ${index} data:`, e);
118124
}
119125
});
120126
} else if (!getRoomResult?.success) {
@@ -306,8 +312,8 @@ export class Game {
306312
LOCALSTORAGE_CANVAS_KEY,
307313
JSON.stringify(this.existingShape)
308314
);
309-
} else if (this.sendMessage && this.roomId) {
310-
this.sendMessage(
315+
} else if (this.handleSendDrawing && this.roomId) {
316+
this.handleSendDrawing(
311317
JSON.stringify({
312318
type: "update",
313319
id: selectedShape.id,
@@ -451,8 +457,8 @@ export class Game {
451457
} catch (e) {
452458
console.error("Error saving shapes to localStorage:", e);
453459
}
454-
} else if (this.sendMessage && this.roomId) {
455-
this.sendMessage(
460+
} else if (this.handleSendDrawing && this.roomId) {
461+
this.handleSendDrawing(
456462
JSON.stringify({
457463
type: "draw",
458464
data: JSON.stringify({
@@ -1063,8 +1069,8 @@ export class Game {
10631069
} catch (e) {
10641070
console.error("Error saving shapes to localStorage:", e);
10651071
}
1066-
} else if (this.sendMessage && this.roomId) {
1067-
this.sendMessage(
1072+
} else if (this.handleSendDrawing && this.roomId) {
1073+
this.handleSendDrawing(
10681074
JSON.stringify({
10691075
type: "eraser",
10701076
data: JSON.stringify({

0 commit comments

Comments
 (0)