From 3737a708f6b7d31c171b77bfd2b634d3519b0196 Mon Sep 17 00:00:00 2001 From: ngc2207 Date: Sun, 5 Jan 2025 03:18:15 +0800 Subject: [PATCH] feat(playground): add auto-focus and position handling on language change in PlaygroundPage --- src/app/playground/page.tsx | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/app/playground/page.tsx b/src/app/playground/page.tsx index e04d08c..506252b 100644 --- a/src/app/playground/page.tsx +++ b/src/app/playground/page.tsx @@ -1,7 +1,7 @@ "use client"; import * as monaco from "monaco-editor"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { Editor } from "@monaco-editor/react"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"; @@ -44,6 +44,21 @@ export default function PlaygroundPage() { const [language, setLanguage] = useState("c"); const file = files[language]; + 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(); + } + } + }, [language]); + return (
@@ -102,16 +117,15 @@ export default function PlaygroundPage() { options={{ automaticLayout: true }} onMount={(editor) => { editorRef.current = editor; - const model = editor.getModel(); + const model = editorRef.current.getModel(); if (model) { const lineCount = model.getLineCount(); const lastLineLength = model.getLineLength(lineCount); - editor.setPosition({ + editorRef.current.setPosition({ lineNumber: lineCount, column: lastLineLength + 1, }); - editor.focus(); - console.log(editor.getModel()?.uri.path); + editorRef.current.focus(); } }} />