|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useRef, useEffect, useState } from "react"; |
| 4 | +import { useParams } from "next/navigation"; |
| 5 | +import { Editor } from "@monaco-editor/react"; |
| 6 | +import type { editor } from "monaco-editor"; |
| 7 | +import * as monaco from "monaco-editor"; |
| 8 | +import * as Y from "yjs"; |
| 9 | +import { WebsocketProvider } from "y-websocket"; |
| 10 | +import { MonacoBinding } from "y-monaco"; |
| 11 | +import { toast } from "react-toastify"; |
| 12 | +import { Separator } from "@/components/ui/separator"; |
| 13 | +import { Card, CardTitle, CardHeader } from "@/components/ui/card"; |
| 14 | +import { |
| 15 | + Select, |
| 16 | + SelectContent, |
| 17 | + SelectGroup, |
| 18 | + SelectItem, |
| 19 | + SelectTrigger, |
| 20 | + SelectValue, |
| 21 | +} from "@/components/ui/select"; |
| 22 | +import { useCollaborationState, useCollaborationActions } from "@/stores/collaboration-store"; |
| 23 | +import { ProgrammingLanguage, ConnectionState } from "@/utils/enums"; |
| 24 | +import { collaborationConfig } from "@/utils/config"; |
| 25 | + |
| 26 | +interface CodeEditorPanelProps { |
| 27 | + readOnly?: boolean; |
| 28 | +} |
| 29 | + |
| 30 | +const programmingLanguageMonacoMap: Record<ProgrammingLanguage, string> = { |
| 31 | + [ProgrammingLanguage.PYTHON]: "python", |
| 32 | + [ProgrammingLanguage.JAVASCRIPT]: "javascript", |
| 33 | + [ProgrammingLanguage.JAVA]: "java", |
| 34 | + [ProgrammingLanguage.CPP]: "cpp", |
| 35 | +}; |
| 36 | + |
| 37 | +const programmingLanguageDisplayMap: Record<ProgrammingLanguage, string> = { |
| 38 | + [ProgrammingLanguage.PYTHON]: "Python", |
| 39 | + [ProgrammingLanguage.JAVASCRIPT]: "JavaScript", |
| 40 | + [ProgrammingLanguage.JAVA]: "Java", |
| 41 | + [ProgrammingLanguage.CPP]: "C++", |
| 42 | +}; |
| 43 | + |
| 44 | +export default function CodeEditorPanel({ readOnly = false }: CodeEditorPanelProps) { |
| 45 | + const params = useParams(); |
| 46 | + const roomId = params?.id as string; |
| 47 | + |
| 48 | + const { roomDetails, documentContent } = useCollaborationState(); |
| 49 | + const { changeLanguage, updateLanguage } = useCollaborationActions(); |
| 50 | + |
| 51 | + const [editorInstance, setEditorInstance] = useState<editor.IStandaloneCodeEditor | null>(null); |
| 52 | + const [monacoInstance, setMonacoInstance] = useState<typeof monaco | null>(null); |
| 53 | + const [connectionStatus, setConnectionStatus] = useState<ConnectionState>( |
| 54 | + ConnectionState.DISCONNECTED, |
| 55 | + ); |
| 56 | + |
| 57 | + const ydocRef = useRef<Y.Doc | null>(null); |
| 58 | + const providerRef = useRef<WebsocketProvider | null>(null); |
| 59 | + const bindingRef = useRef<MonacoBinding | null>(null); |
| 60 | + |
| 61 | + const currentLanguage = roomDetails?.programmingLanguage || ProgrammingLanguage.PYTHON; |
| 62 | + const monacoLanguage = programmingLanguageMonacoMap[currentLanguage]; |
| 63 | + |
| 64 | + // Initialize Yjs and WebSocket provider for active rooms |
| 65 | + useEffect(() => { |
| 66 | + if (!roomId || !roomDetails?.isActive || !editorInstance || providerRef.current) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + // Create Yjs document |
| 71 | + const ydoc = new Y.Doc(); |
| 72 | + ydocRef.current = ydoc; |
| 73 | + |
| 74 | + // Create WebSocket provider |
| 75 | + const wsUrl = collaborationConfig.WS_URL; |
| 76 | + const provider = new WebsocketProvider(wsUrl, roomId, ydoc); |
| 77 | + providerRef.current = provider; |
| 78 | + |
| 79 | + // Create Monaco binding |
| 80 | + const binding = new MonacoBinding( |
| 81 | + ydoc.getText("monaco"), |
| 82 | + editorInstance.getModel()!, |
| 83 | + new Set([editorInstance]), |
| 84 | + provider.awareness, |
| 85 | + ); |
| 86 | + bindingRef.current = binding; |
| 87 | + |
| 88 | + setConnectionStatus(ConnectionState.CONNECTING); |
| 89 | + |
| 90 | + // Listen for connection status |
| 91 | + provider.on("status", (event: { status: string }) => { |
| 92 | + if (event.status === ConnectionState.CONNECTED) { |
| 93 | + setConnectionStatus(ConnectionState.CONNECTED); |
| 94 | + toast.success("Connected to collaboration session"); |
| 95 | + } else if (event.status === ConnectionState.DISCONNECTED) { |
| 96 | + setConnectionStatus(ConnectionState.DISCONNECTED); |
| 97 | + toast.warn("Disconnected from collaboration session"); |
| 98 | + } |
| 99 | + }); |
| 100 | + |
| 101 | + // Listen for custom messages |
| 102 | + const handleMessage = (event: MessageEvent) => { |
| 103 | + try { |
| 104 | + const message = JSON.parse(event.data); |
| 105 | + if (message.type === "language-change-notification") { |
| 106 | + const programmingLanguage = message.data.language as ProgrammingLanguage; |
| 107 | + updateLanguage(programmingLanguage); |
| 108 | + toast.info(`Language changed to ${programmingLanguageDisplayMap[programmingLanguage]}`); |
| 109 | + } else if (message.type === "room-close-notification") { |
| 110 | + toast.warn("The collaboration room has been closed"); |
| 111 | + } |
| 112 | + } catch { |
| 113 | + // Ignore non-JSON messages (e.g., Yjs updates) |
| 114 | + } |
| 115 | + }; |
| 116 | + provider.ws?.addEventListener("message", handleMessage); |
| 117 | + |
| 118 | + // Cleanup |
| 119 | + return () => { |
| 120 | + provider.ws?.removeEventListener("message", handleMessage); |
| 121 | + binding.destroy(); |
| 122 | + provider.destroy(); |
| 123 | + ydoc.destroy(); |
| 124 | + }; |
| 125 | + }, [roomId, roomDetails?.isActive, editorInstance, updateLanguage]); |
| 126 | + |
| 127 | + // Update Monaco language when room language changes |
| 128 | + useEffect(() => { |
| 129 | + if (editorInstance && monacoLanguage && monacoInstance) { |
| 130 | + const model = editorInstance.getModel(); |
| 131 | + if (model) { |
| 132 | + monacoInstance.editor.setModelLanguage(model, monacoLanguage); |
| 133 | + } |
| 134 | + } |
| 135 | + }, [editorInstance, monacoLanguage, monacoInstance]); |
| 136 | + |
| 137 | + // Handle language change from dropdown |
| 138 | + const handleLanguageChange = async (language: ProgrammingLanguage) => { |
| 139 | + if (!roomId || readOnly) return; |
| 140 | + changeLanguage(roomId, language).catch((err) => { |
| 141 | + console.error("Failed to change language:", err); |
| 142 | + }); |
| 143 | + }; |
| 144 | + |
| 145 | + // Handle editor mount |
| 146 | + const handleEditorDidMount = ( |
| 147 | + editorRef: editor.IStandaloneCodeEditor, |
| 148 | + monacoRef: typeof monaco, |
| 149 | + ) => { |
| 150 | + setEditorInstance(editorRef); |
| 151 | + setMonacoInstance(monacoRef); |
| 152 | + |
| 153 | + // Set document content for read-only mode |
| 154 | + if (readOnly && documentContent) { |
| 155 | + editorRef.setValue(documentContent); |
| 156 | + } |
| 157 | + }; |
| 158 | + |
| 159 | + // Connection status badge |
| 160 | + const getConnectionBadge = () => { |
| 161 | + if (readOnly || !roomDetails?.isActive) { |
| 162 | + return ( |
| 163 | + <div className="flex items-center gap-2"> |
| 164 | + <div className="w-2 h-2 rounded-full bg-gray-500" /> |
| 165 | + <span className="text-sm text-muted-foreground">Read-Only</span> |
| 166 | + </div> |
| 167 | + ); |
| 168 | + } |
| 169 | + |
| 170 | + const statusConfig = { |
| 171 | + [ConnectionState.CONNECTING]: { color: "bg-yellow-500", text: "Connecting..." }, |
| 172 | + [ConnectionState.CONNECTED]: { color: "bg-green-500", text: "Connected" }, |
| 173 | + [ConnectionState.DISCONNECTED]: { color: "bg-red-500", text: "Disconnected" }, |
| 174 | + [ConnectionState.RECONNECTING]: { color: "bg-yellow-500", text: "Reconnecting..." }, |
| 175 | + }; |
| 176 | + |
| 177 | + const config = statusConfig[connectionStatus]; |
| 178 | + |
| 179 | + return ( |
| 180 | + <div className="flex items-center gap-2"> |
| 181 | + <div className={`w-2 h-2 rounded-full ${config.color}`} /> |
| 182 | + <span className="text-sm text-muted-foreground">{config.text}</span> |
| 183 | + </div> |
| 184 | + ); |
| 185 | + }; |
| 186 | + |
| 187 | + return ( |
| 188 | + <Card className="rounded-none min-h-full h-auto w-full"> |
| 189 | + <CardHeader> |
| 190 | + <div className="flex items-center justify-between"> |
| 191 | + <div className="flex items-center gap-4"> |
| 192 | + <CardTitle>Editor</CardTitle> |
| 193 | + <Select |
| 194 | + value={currentLanguage} |
| 195 | + onValueChange={handleLanguageChange} |
| 196 | + disabled={readOnly} |
| 197 | + > |
| 198 | + <SelectTrigger className="w-[220px]"> |
| 199 | + <SelectValue placeholder="Language" /> |
| 200 | + </SelectTrigger> |
| 201 | + <SelectContent className="max-h-[300px] overflow-y-auto"> |
| 202 | + <SelectGroup> |
| 203 | + {Object.values(ProgrammingLanguage).map((lang) => ( |
| 204 | + <SelectItem key={lang} value={lang}> |
| 205 | + {programmingLanguageDisplayMap[lang]} |
| 206 | + </SelectItem> |
| 207 | + ))} |
| 208 | + </SelectGroup> |
| 209 | + </SelectContent> |
| 210 | + </Select> |
| 211 | + </div> |
| 212 | + {getConnectionBadge()} |
| 213 | + </div> |
| 214 | + </CardHeader> |
| 215 | + <Separator /> |
| 216 | + <Editor |
| 217 | + height="60vh" |
| 218 | + language={monacoLanguage} |
| 219 | + theme="vs-dark" |
| 220 | + options={{ |
| 221 | + readOnly: readOnly, |
| 222 | + fontSize: 14, |
| 223 | + }} |
| 224 | + onMount={handleEditorDidMount} |
| 225 | + /> |
| 226 | + </Card> |
| 227 | + ); |
| 228 | +} |
0 commit comments