index.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import './env'
  2. import * as monaco from 'monaco-editor'
  3. import { registerCustomTheme } from './themes'
  4. import { registerLanguages } from './languages'
  5. import { createEditor, createModel } from './editor'
  6. import { watchEffect, type WatchHandle } from 'vue'
  7. import { usePersonalization } from '@/composable/usePersonalization'
  8. let initialized = false
  9. const { isDark } = usePersonalization()
  10. let stopThemeWatch: WatchHandle | undefined
  11. function initMonaco() {
  12. if (initialized) return
  13. initialized = true
  14. registerCustomTheme()
  15. registerLanguages()
  16. // 统一切换 Monaco 主题
  17. stopThemeWatch ??= watchEffect(() => {
  18. monaco.editor.setTheme(isDark.value ? 'custom-dark' : 'custom')
  19. }, {})
  20. }
  21. export interface MonacoModelParam {
  22. initValue: string
  23. language: string
  24. uri?: string
  25. }
  26. export interface MonacoEditorParam {
  27. el: HTMLElement
  28. options: monaco.editor.IStandaloneEditorConstructionOptions
  29. }
  30. export interface MonacoEditor {
  31. model: monaco.editor.ITextModel
  32. editor: monaco.editor.IStandaloneCodeEditor
  33. }
  34. export function createMonacoEditor(
  35. model: MonacoModelParam,
  36. editor: MonacoEditorParam,
  37. ): MonacoEditor {
  38. initMonaco()
  39. const m = createModel(model.initValue, model.language, model.uri)
  40. const e = createEditor(editor.el, {
  41. model: m,
  42. ...editor.options,
  43. })
  44. return {
  45. model: m,
  46. editor: e,
  47. }
  48. }