77 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-07-06 14:13:27 +08:00
import { ref, onBeforeUnmount, nextTick } from 'vue'
2022-07-06 20:48:59 +08:00
import { useDesignStore } from '@/store/modules/designStore/designStore'
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
2022-07-06 14:13:27 +08:00
export const useMonacoEditor = (language = 'javascript') => {
2022-07-06 20:48:59 +08:00
const designStore = useDesignStore()
let monacoEditor: monaco.editor.IStandaloneCodeEditor | null = null
let initReadOnly = false
2022-07-06 14:13:27 +08:00
const el = ref<HTMLElement | null>(null)
// 格式化
const onFormatDoc = async () => {
await monacoEditor?.getAction('monacoEditor.action.formatDocument')?.run()
}
// 更新
const updateVal = (val: string) => {
nextTick(async () => {
monacoEditor?.setValue(val)
initReadOnly && monacoEditor?.updateOptions({ readOnly: false })
2022-07-06 14:13:27 +08:00
await onFormatDoc()
initReadOnly && monacoEditor?.updateOptions({ readOnly: true })
2022-07-06 14:13:27 +08:00
})
}
2022-07-06 14:13:27 +08:00
// 创建实例
const createEditor = (editorOption: monaco.editor.IStandaloneEditorConstructionOptions = {}) => {
if (!el.value) return
const javascriptModel = monaco.editor.createModel('', language)
initReadOnly = !!editorOption.readOnly
2022-07-06 14:13:27 +08:00
// 创建
monacoEditor = monaco.editor.create(el.value, {
model: javascriptModel,
2022-07-06 20:48:59 +08:00
// 是否启用预览图
minimap: { enabled: false },
// 圆角
roundedSelection: true,
// 主题
theme: designStore.getDarkTheme ? 'vs-dark' : 'vs',
// 主键
2022-07-06 14:13:27 +08:00
multiCursorModifier: 'ctrlCmd',
2022-07-06 20:48:59 +08:00
// 滚动条
2022-07-06 14:13:27 +08:00
scrollbar: {
verticalScrollbarSize: 8,
horizontalScrollbarSize: 8
},
2022-07-06 20:48:59 +08:00
// 行号
lineNumbers: 'off',
// tab大小
2022-07-06 14:13:27 +08:00
tabSize: 2,
2022-07-06 20:48:59 +08:00
//字体大小
fontSize: 16,
// 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
autoIndent: 'advanced',
// 自动布局
automaticLayout: true,
2022-07-06 14:13:27 +08:00
...editorOption
})
return monacoEditor
}
2022-07-06 14:13:27 +08:00
// 卸载
onBeforeUnmount(() => {
if (monacoEditor) monacoEditor.dispose()
})
return {
2022-07-06 14:13:27 +08:00
el,
updateVal,
getEditor: () => monacoEditor,
createEditor,
onFormatDoc
}
}