feat(editor): add theme support to code editor

This commit is contained in:
ngc2207 2024-12-31 20:59:04 +08:00
parent e13fff0be4
commit 49da57872e
4 changed files with 29 additions and 1 deletions

View File

@ -29,6 +29,7 @@
"zustand": "^5.0.2" "zustand": "^5.0.2"
}, },
"devDependencies": { "devDependencies": {
"@shikijs/monaco": "^1.24.4",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
@ -36,6 +37,7 @@
"eslint-config-next": "15.0.3", "eslint-config-next": "15.0.3",
"postcss": "^8", "postcss": "^8",
"prisma": "^6.1.0", "prisma": "^6.1.0",
"shiki": "^1.24.4",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"typescript": "^5" "typescript": "^5"
} }

21
src/constants/themes.ts Normal file
View File

@ -0,0 +1,21 @@
import { createHighlighter } from "shiki";
import { Monaco } from "@monaco-editor/react";
import { shikiToMonaco } from "@shikijs/monaco";
import { SUPPORTED_LANGUAGES } from "./languages";
export const SUPPORTED_THEMES = ["vitesse-dark", "vitesse-light"];
export const DEFAULT_THEME = SUPPORTED_THEMES[0];
export const highlightMonacoEditor = async (monaco: Monaco) => {
const highlighter = await createHighlighter({
themes: SUPPORTED_THEMES,
langs: SUPPORTED_LANGUAGES.map((lang) => lang.key),
});
for (const lang of SUPPORTED_LANGUAGES) {
monaco.languages.register({ id: lang.key });
}
shikiToMonaco(highlighter, monaco);
};

View File

@ -1,5 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import { CodeEditorState } from "@/types"; import { CodeEditorState } from "@/types";
import { DEFAULT_THEME } from "@/constants/themes";
import { DEFAULT_LANGUAGE } from "@/constants/languages"; import { DEFAULT_LANGUAGE } from "@/constants/languages";
import { persist, createJSONStorage } from "zustand/middleware"; import { persist, createJSONStorage } from "zustand/middleware";
@ -7,10 +8,12 @@ export const useCodeEditorStore = create<CodeEditorState>()(
persist( persist(
(set, get) => ({ (set, get) => ({
language: DEFAULT_LANGUAGE, language: DEFAULT_LANGUAGE,
theme: DEFAULT_THEME,
setLanguage: (language: string) => set({ language }), setLanguage: (language: string) => set({ language }),
setTheme: (theme: string) => set({ theme }),
}), }),
{ {
name: "language-storage", name: "code-editor-storage",
storage: createJSONStorage(() => localStorage), storage: createJSONStorage(() => localStorage),
} }
) )

View File

@ -1,5 +1,7 @@
export interface CodeEditorState { export interface CodeEditorState {
language: string; language: string;
theme: string;
setLanguage: (language: string) => void; setLanguage: (language: string) => void;
setTheme: (theme: string) => void;
} }