feat(playground): add auto-focus and position handling on language change in PlaygroundPage

This commit is contained in:
ngc2207 2025-01-05 03:18:15 +08:00
parent 2c7630c286
commit 3737a708f6

View File

@ -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<keyof typeof files>("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 (
<div className="h-full flex flex-col">
<Tabs defaultValue={language as string}>
@ -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();
}
}}
/>