|
| 1 | +import React, { createContext, useState, useContext, ReactNode, useEffect, useMemo } from "react"; |
| 2 | +import * as Y from "yjs"; |
| 3 | +import * as monaco from "monaco-editor"; |
| 4 | +import { MonacoBinding } from "y-monaco"; |
| 5 | +import { WebsocketProvider } from "y-websocket"; |
| 6 | +import { useAuth } from "./AuthContext"; |
| 7 | +import { toast } from "react-toastify"; |
| 8 | +import { COLLABORATION_AWARENESS_KEYS, COLLABORATION_YMAP_KEYS } from "presentation/utils/constants"; |
| 9 | +import PistonClient from "data/piston/PistonClient"; |
| 10 | +import { Language } from "domain/entities/Language"; |
| 11 | +import { CodeExecResult } from "domain/entities/CodeExecResult"; |
| 12 | + |
| 13 | +interface CollaborationContextType { |
| 14 | + onEditorIsMounted: (editor: monaco.editor.IStandaloneCodeEditor) => void; |
| 15 | + selectedLanguage: Language; |
| 16 | + languages: Language[]; |
| 17 | + handleChangeLanguage: (lang: Language) => void; |
| 18 | + handleExecuteCode: () => Promise<void>; |
| 19 | + isExecuting: boolean; |
| 20 | + execResult: CodeExecResult | null; |
| 21 | + setRoomId: (roomId: string) => void; |
| 22 | + connectedUsers: string[]; |
| 23 | +} |
| 24 | + |
| 25 | +const CollaborationContext = createContext<CollaborationContextType | undefined>(undefined); |
| 26 | + |
| 27 | +export const CollaborationProvider: React.FC<{ children: ReactNode }> = ({ children }) => { |
| 28 | + const { user } = useAuth(); |
| 29 | + const username = user?.username; |
| 30 | + |
| 31 | + const { USERNAME } = COLLABORATION_AWARENESS_KEYS; |
| 32 | + const { SELECTED_LANGUAGE } = COLLABORATION_YMAP_KEYS; |
| 33 | + |
| 34 | + const [selectedLanguage, setSelectedLanguage] = useState<Language>({ |
| 35 | + language: "javascript", |
| 36 | + version: "1.32.3", |
| 37 | + alias: "Javascript" |
| 38 | + }); |
| 39 | + |
| 40 | + const ydoc = useMemo(() => new Y.Doc(), []); |
| 41 | + const ymap: Y.Map<any> = useMemo(() => ydoc.getMap("sharedMap"), [ydoc]); |
| 42 | + |
| 43 | + const [roomId, setRoomId] = useState<string | null>(null); |
| 44 | + |
| 45 | + const [languages, setLanguages] = useState<Language[]>([]); |
| 46 | + const [execResult, setExecResult] = useState<CodeExecResult | null>(null); |
| 47 | + const [isExecuting, setIsExecuting] = useState<boolean>(false); |
| 48 | + const [connectedUsers, setConnectedUsers] = useState<string[]>([]); |
| 49 | + |
| 50 | + const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null); |
| 51 | + const [provider, setProvider] = useState<WebsocketProvider | null>(null); |
| 52 | + const [binding, setBinding] = useState<MonacoBinding | null>(null); |
| 53 | + |
| 54 | + // This effect manages the lifetime of the yjs doc and the provider |
| 55 | + useEffect(() => { |
| 56 | + if (roomId == null) { |
| 57 | + return; |
| 58 | + } |
| 59 | + const provider = new WebsocketProvider("ws://localhost:1234", roomId, ydoc); |
| 60 | + setProvider(provider); |
| 61 | + |
| 62 | + provider.awareness.setLocalStateField(USERNAME, username); |
| 63 | + provider.awareness.on("change", (update: any) => { |
| 64 | + const users = Array.from(provider.awareness.getStates().values()); |
| 65 | + setConnectedUsers(users.map((user) => user[USERNAME])); |
| 66 | + // TODO: Some UI feedback about connection status of the other user |
| 67 | + }); |
| 68 | + |
| 69 | + return () => { |
| 70 | + provider?.destroy(); |
| 71 | + ydoc?.destroy(); |
| 72 | + }; |
| 73 | + }, [ydoc, roomId]); |
| 74 | + |
| 75 | + // This effect manages the lifetime of the editor binding |
| 76 | + useEffect(() => { |
| 77 | + if (provider == null || editor == null || editor.getModel() == null) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + const binding = new MonacoBinding( |
| 82 | + ydoc.getText("monaco"), |
| 83 | + editor.getModel()!, |
| 84 | + new Set([editor]), |
| 85 | + provider?.awareness |
| 86 | + ); |
| 87 | + |
| 88 | + setBinding(binding); |
| 89 | + |
| 90 | + ymap.observe((event) => { |
| 91 | + event.changes.keys.forEach((change, key) => { |
| 92 | + if (key === SELECTED_LANGUAGE) { |
| 93 | + const language: Language = ymap.get(SELECTED_LANGUAGE); |
| 94 | + setSelectedLanguage(language); |
| 95 | + const model = editor.getModel(); |
| 96 | + monaco.editor.setModelLanguage(model!, language.language); |
| 97 | + } |
| 98 | + }); |
| 99 | + }); |
| 100 | + |
| 101 | + // Set the editor's language |
| 102 | + const language: Language = ymap.get(SELECTED_LANGUAGE); |
| 103 | + const model = editor.getModel(); |
| 104 | + monaco.editor.setModelLanguage(model!, language?.language ?? "javascript"); |
| 105 | + |
| 106 | + return () => { |
| 107 | + binding.destroy(); |
| 108 | + }; |
| 109 | + }, [ydoc, provider, editor, ymap]); |
| 110 | + |
| 111 | + useEffect(() => { |
| 112 | + initialiseLanguages(); |
| 113 | + }, []); |
| 114 | + |
| 115 | + const initialiseLanguages = async () => { |
| 116 | + // Initialise language dropdown |
| 117 | + const allLanguages = monaco.languages.getLanguages(); |
| 118 | + const pistonLanguageVersions = await PistonClient.getLanguageVersions(); |
| 119 | + setLanguages( |
| 120 | + allLanguages |
| 121 | + .filter((lang) => pistonLanguageVersions.some((pistonLang: any) => pistonLang.language === lang.id)) |
| 122 | + .map((lang) => ({ |
| 123 | + alias: lang.aliases && lang.aliases.length > 0 ? lang.aliases[0] : lang.id, |
| 124 | + language: lang.id, |
| 125 | + version: pistonLanguageVersions.find((pistonLang: any) => pistonLang.language === lang.id)?.version |
| 126 | + })) |
| 127 | + ); |
| 128 | + }; |
| 129 | + |
| 130 | + const handleChangeLanguage = (lang: Language) => { |
| 131 | + ymap.set(SELECTED_LANGUAGE, lang); |
| 132 | + }; |
| 133 | + |
| 134 | + const handleExecuteCode = async () => { |
| 135 | + try { |
| 136 | + setIsExecuting(true); |
| 137 | + const sourceCode = editor?.getValue(); |
| 138 | + if (!sourceCode) { |
| 139 | + // TODO |
| 140 | + return; |
| 141 | + } |
| 142 | + const output: CodeExecResult = await PistonClient.executeCode(selectedLanguage, sourceCode); |
| 143 | + setExecResult(output); |
| 144 | + } catch (e) { |
| 145 | + toast.error("There was an issue running the code"); |
| 146 | + } finally { |
| 147 | + setIsExecuting(false); |
| 148 | + } |
| 149 | + }; |
| 150 | + |
| 151 | + const onEditorIsMounted = (editor: monaco.editor.IStandaloneCodeEditor) => { |
| 152 | + setEditor(editor); |
| 153 | + }; |
| 154 | + |
| 155 | + return ( |
| 156 | + <CollaborationContext.Provider |
| 157 | + value={{ |
| 158 | + onEditorIsMounted, |
| 159 | + setRoomId, |
| 160 | + selectedLanguage, |
| 161 | + languages, |
| 162 | + handleChangeLanguage, |
| 163 | + handleExecuteCode, |
| 164 | + isExecuting, |
| 165 | + execResult, |
| 166 | + connectedUsers |
| 167 | + }} |
| 168 | + > |
| 169 | + {children} |
| 170 | + </CollaborationContext.Provider> |
| 171 | + ); |
| 172 | +}; |
| 173 | + |
| 174 | +export const useCollaboration = () => { |
| 175 | + const context = useContext(CollaborationContext); |
| 176 | + if (!context) { |
| 177 | + throw new Error("useCollaboration must be used within a CollaborationProvider"); |
| 178 | + } |
| 179 | + return context; |
| 180 | +}; |
0 commit comments