Skip to content

Commit 9bc6f1b

Browse files
committed
feat: use monaco editor
1 parent 322406a commit 9bc6f1b

File tree

1 file changed

+41
-27
lines changed

1 file changed

+41
-27
lines changed
Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<script setup lang='ts'>
2-
import CodeMirror from 'codemirror'
2+
import type { editor as MonacoEditor } from 'monaco-editor'
3+
import * as monaco from 'monaco-editor'
34
import { useStore } from '@/stores'
45
import { removeLeft } from '@/utils'
56
@@ -18,22 +19,46 @@ const code = useLocalStorage(`formCustomConfig`, removeLeft(`
1819
})
1920
`).trim())
2021
21-
const formCustomTextarea = useTemplateRef<HTMLTextAreaElement>(`formCustomTextarea`)
22+
const editorRef = useTemplateRef<HTMLDivElement>(`editorRef`)
2223
23-
const editor = ref<CodeMirror.EditorFromTextArea | null>(null)
24+
const editor = ref<MonacoEditor.IStandaloneCodeEditor | null>(null)
2425
2526
onMounted(() => {
26-
editor.value = markRaw(CodeMirror.fromTextArea(formCustomTextarea.value!, {
27-
mode: `javascript`,
28-
theme: store.isDark ? `darcula` : `xq-light`,
29-
lineNumbers: true,
30-
}))
27+
editor.value = monaco.editor.create(editorRef.value!, {
28+
value: code.value,
29+
language: `javascript`,
30+
theme: store.isDark ? `vs-dark` : `vs`,
31+
lineNumbers: `on`,
32+
automaticLayout: true,
33+
fontSize: 12,
34+
lineHeight: 18,
35+
})
36+
})
3137
32-
// 嵌套使用 nextTick 才能确保生效,具体原因未知
33-
nextTick(() => {
34-
nextTick(() => {
35-
editor.value?.setValue(code.value)
38+
function updateEditorStyle(fontSize: number, lineHeight: number) {
39+
if (editor.value) {
40+
editor.value.updateOptions({
41+
fontSize,
42+
lineHeight,
3643
})
44+
}
45+
}
46+
47+
onMounted(() => {
48+
const updateStyle = () => {
49+
if (window.innerWidth >= 768) {
50+
updateEditorStyle(14, 24)
51+
}
52+
else {
53+
updateEditorStyle(12, 20)
54+
}
55+
}
56+
57+
window.addEventListener(`resize`, updateStyle)
58+
updateStyle()
59+
60+
onUnmounted(() => {
61+
window.removeEventListener(`resize`, updateStyle)
3762
})
3863
})
3964
@@ -46,10 +71,10 @@ function formCustomSave() {
4671

4772
<template>
4873
<div class="space-y-4 min-w-0">
49-
<div class="h-60 border flex flex-col">
50-
<textarea
51-
ref="formCustomTextarea"
52-
placeholder="Your custom code here."
74+
<div class="h-60 border flex flex-col rounded-md">
75+
<div
76+
ref="editorRef"
77+
class="flex-1"
5378
/>
5479
</div>
5580
<Button
@@ -68,15 +93,4 @@ function formCustomSave() {
6893
</template>
6994

7095
<style scoped>
71-
/* 覆盖全局的 overflow-x: hidden 设置 */
72-
:deep(.CodeMirror-scroll) {
73-
overflow-x: auto !important;
74-
overflow-y: auto !important;
75-
}
76-
77-
@media (max-width: 768px) {
78-
:deep(.CodeMirror) {
79-
font-size: 12px;
80-
}
81-
}
8296
</style>

0 commit comments

Comments
 (0)