From 6297419aad1486dbfc5e3bcd51a929d2d753b58d Mon Sep 17 00:00:00 2001 From: cfngc4594 Date: Sun, 9 Mar 2025 10:48:03 +0800 Subject: [PATCH] feat(code-editor): persist code changes and apply problem templates --- src/components/code-editor.tsx | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/components/code-editor.tsx b/src/components/code-editor.tsx index 28daa91..4790bc0 100644 --- a/src/components/code-editor.tsx +++ b/src/components/code-editor.tsx @@ -4,6 +4,7 @@ import dynamic from "next/dynamic"; import { Skeleton } from "./ui/skeleton"; import { highlighter } from "@/lib/shiki"; import type { editor } from "monaco-editor"; +import { EditorLanguage } from "@prisma/client"; import { shikiToMonaco } from "@shikijs/monaco"; import type { Monaco } from "@monaco-editor/react"; import { useCallback, useEffect, useRef } from "react"; @@ -35,7 +36,15 @@ const Editor = dynamic( } ); -export default function CodeEditor() { +interface CodeEditorProps { + problemId: string; + templates: { language: EditorLanguage; template: string }[]; +} + +export default function CodeEditor({ + problemId, + templates, +}: CodeEditorProps) { const { hydrated, language, @@ -44,11 +53,30 @@ export default function CodeEditor() { editorConfig, isLspEnabled, setEditor, + setValue, } = useCodeEditorStore(); const { monacoTheme } = useMonacoTheme(); const editorRef = useRef(null); const monacoLanguageClientRef = useRef(null); + const valueStorageKey = `value_${problemId}_${language}`; + + useEffect(() => { + const storedValue = localStorage.getItem(valueStorageKey); + if (storedValue !== null) { + setValue(storedValue); + } else { + const template = templates.find((t) => t.language === language); + if (template) setValue(template.template); + } + }, [valueStorageKey, setValue, templates, language]) + + const handleEditorChange = (value: string | undefined, event: editor.IModelContentChangedEvent) => { + if (value === undefined) return; + setValue(value); + localStorage.setItem(valueStorageKey, value); + } + // Connect to LSP only if enabled const connectLSP = useCallback(async () => { if (!(isLspEnabled && language && editorRef.current)) return; @@ -119,6 +147,7 @@ export default function CodeEditor() { value={value} beforeMount={handleEditorWillMount} onMount={handleEditorDidMount} + onChange={handleEditorChange} options={editorConfig} loading={} className="h-full w-full py-2"