2022-07-06 14:13:27 +08:00
|
|
|
import { ref, onBeforeUnmount, nextTick } from 'vue'
|
2022-07-05 21:44:16 +08:00
|
|
|
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-05 21:44:16 +08:00
|
|
|
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)
|
2022-07-05 21:44:16 +08:00
|
|
|
initReadOnly && monacoEditor?.updateOptions({ readOnly: false })
|
2022-07-06 14:13:27 +08:00
|
|
|
await onFormatDoc()
|
2022-07-05 21:44:16 +08:00
|
|
|
initReadOnly && monacoEditor?.updateOptions({ readOnly: true })
|
2022-07-06 14:13:27 +08:00
|
|
|
})
|
2022-07-05 21:44:16 +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)
|
2022-07-05 21:44:16 +08:00
|
|
|
initReadOnly = !!editorOption.readOnly
|
2022-07-06 14:13:27 +08:00
|
|
|
// 创建
|
|
|
|
monacoEditor = monaco.editor.create(el.value, {
|
|
|
|
model: javascriptModel,
|
|
|
|
minimap: { enabled: true },
|
|
|
|
roundedSelection: false,
|
|
|
|
theme: 'vs-dark',
|
|
|
|
multiCursorModifier: 'ctrlCmd',
|
|
|
|
scrollbar: {
|
|
|
|
verticalScrollbarSize: 8,
|
|
|
|
horizontalScrollbarSize: 8
|
|
|
|
},
|
|
|
|
tabSize: 2,
|
|
|
|
fontSize: 16, //字体大小
|
|
|
|
autoIndent: 'advanced', //自动布局
|
|
|
|
automaticLayout: true, // 自适应宽高
|
|
|
|
...editorOption
|
|
|
|
})
|
|
|
|
|
2022-07-05 21:44:16 +08:00
|
|
|
return monacoEditor
|
|
|
|
}
|
2022-07-06 14:13:27 +08:00
|
|
|
|
|
|
|
// 卸载
|
|
|
|
onBeforeUnmount(() => {
|
|
|
|
if (monacoEditor) monacoEditor.dispose()
|
|
|
|
})
|
|
|
|
|
2022-07-05 21:44:16 +08:00
|
|
|
return {
|
2022-07-06 14:13:27 +08:00
|
|
|
el,
|
2022-07-05 21:44:16 +08:00
|
|
|
updateVal,
|
|
|
|
getEditor: () => monacoEditor,
|
|
|
|
createEditor,
|
|
|
|
onFormatDoc
|
|
|
|
}
|
|
|
|
}
|