diff --git a/src/app/playground/page.tsx b/src/app/playground/page.tsx index 94ba1db..0014690 100644 --- a/src/app/playground/page.tsx +++ b/src/app/playground/page.tsx @@ -51,31 +51,43 @@ export default function PlaygroundPage() { const languageClientRef = useRef(null); useEffect(() => { - if (editorRef.current) { - const model = editorRef.current.getModel(); - if (model) { - const lineCount = model.getLineCount(); - const lastLineLength = model.getLineLength(lineCount); - editorRef.current.setPosition({ - lineNumber: lineCount, - column: lastLineLength + 1, - }); - editorRef.current.focus(); - if (webSocketRef.current) { - webSocketRef.current.close(); - webSocketRef.current = null; - } - if (languageClientRef.current) { - languageClientRef.current.stop(); - languageClientRef.current = null; - } - connectToLanguageServer(language, webSocketRef).then( - (languageClient) => { - languageClientRef.current = languageClient; + const handleLanguageChange = async () => { + if (editorRef.current) { + const model = editorRef.current.getModel(); + if (model) { + const lineCount = model.getLineCount(); + const lastLineLength = model.getLineLength(lineCount); + editorRef.current.setPosition({ + lineNumber: lineCount, + column: lastLineLength + 1, + }); + editorRef.current.focus(); + if (languageClientRef.current) { + await languageClientRef.current.stop(); + languageClientRef.current = null; } - ); + if ( + webSocketRef.current && + webSocketRef.current.readyState !== WebSocket.CLOSED && + webSocketRef.current.readyState !== WebSocket.CLOSING + ) { + webSocketRef.current.close(); + webSocketRef.current = null; + } + try { + const languageClient = await connectToLanguageServer( + language, + webSocketRef + ); + languageClientRef.current = languageClient; + } catch (error) { + console.error("Failed to connect to language server:", error); + } + } } - } + }; + + handleLanguageChange(); }, [language]); return ( @@ -146,11 +158,13 @@ export default function PlaygroundPage() { column: lastLineLength + 1, }); editorRef.current.focus(); - connectToLanguageServer(language, webSocketRef).then( - (languageClient) => { + connectToLanguageServer(language, webSocketRef) + .then((languageClient) => { languageClientRef.current = languageClient; - } - ); + }) + .catch((error) => { + console.error("Failed to connect to language server:", error); + }); } } }}