diff --git a/src/constants/editor/values.ts b/src/constants/editor/values.ts new file mode 100644 index 0000000..cf4e68c --- /dev/null +++ b/src/constants/editor/values.ts @@ -0,0 +1,23 @@ +export const DEFAULT_VALUE = [ + { + key: "c", + value: `#include +int main() { + printf("Hello, World!"); + return 0; +}`, + }, + { + key: "cpp", + value: `#include +using namespace std; +int main() { + cout << "Hello, World!"; + return 0; +}`, + }, + { + key: "python", + value: `print("Hello, World!")`, + }, +]; diff --git a/src/store/useCodeEditorStore.ts b/src/store/useCodeEditorStore.ts index e20c53d..cc77fd1 100644 --- a/src/store/useCodeEditorStore.ts +++ b/src/store/useCodeEditorStore.ts @@ -2,22 +2,42 @@ import { create } from "zustand"; import { editor } from "monaco-editor"; import { CodeEditorState } from "@/types"; import { DEFAULT_THEME } from "@/constants/editor/themes"; +import { DEFAULT_VALUE } from "@/constants/editor/values"; import { DEFAULT_FONT_SIZE } from "@/constants/editor/options"; import { DEFAULT_LANGUAGE } from "@/constants/editor/languages"; import { persist, createJSONStorage } from "zustand/middleware"; +const getSavedCode = (language: string) => + localStorage.getItem(`code-editor-${language}`) || + DEFAULT_VALUE.find((v) => v.key === language)?.value || + ""; + +const saveCode = (language: string, code: string) => + localStorage.setItem(`code-editor-${language}`, code); + export const useCodeEditorStore = create()( persist( - (set) => ({ + (set, get) => ({ language: DEFAULT_LANGUAGE, theme: DEFAULT_THEME, fontSize: DEFAULT_FONT_SIZE, editor: null, - setLanguage: (language: string) => set({ language }), + setLanguage: (language: string) => { + const { editor: currentEditor, language: currentLanguage } = get(); + const currentCode = currentEditor?.getValue() || ""; + if (currentEditor) saveCode(currentLanguage, currentCode); + const savedCode = getSavedCode(language); + if (savedCode && currentEditor) currentEditor.setValue(savedCode); + set({ language }); + }, setTheme: (theme: string) => set({ theme }), setFontSize: (fontSize: number) => set({ fontSize }), - setEditor: (editor: editor.IStandaloneCodeEditor) => set({ editor }), + setEditor: (editor: editor.IStandaloneCodeEditor) => { + const savedCode = getSavedCode(get().language); + if (savedCode) editor.setValue(savedCode); + set({ editor }); + }, }), { name: "code-editor-storage",