-
Notifications
You must be signed in to change notification settings - Fork 150
/
CodeMirror.vue
109 lines (93 loc) · 2.02 KB
/
CodeMirror.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<template>
<div class="editor" ref="el"></div>
</template>
<script setup lang="ts">
import type { ModeSpec, ModeSpecOptions } from 'codemirror'
import { ref, onMounted, watchEffect, inject } from 'vue'
import { debounce } from '../utils'
import CodeMirror from './codemirror'
export interface Props {
mode?: string | ModeSpec<ModeSpecOptions>
value?: string
readonly?: boolean
}
const props = withDefaults(defineProps<Props>(), {
mode: 'htmlmixed',
value: '',
readonly: false,
})
const emit = defineEmits<{
save: [string]
}>()
const el = ref()
const needAutoResize = inject('autoresize')
onMounted(() => {
const addonOptions = props.readonly
? {}
: {
autoCloseBrackets: true,
autoCloseTags: true,
foldGutter: true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
keyMap: 'sublime',
}
function save() {
emit('save', editor.getValue())
}
const editor = CodeMirror(el.value!, {
value: '',
mode: props.mode,
readOnly: props.readonly,
tabSize: 2,
lineWrapping: true,
lineNumbers: true,
...addonOptions,
})
const autoSave = inject<number>('autoSave')
if (autoSave > 0) {
editor.on('change', debounce(save, autoSave))
}
editor.on('blur', () => {
save()
})
el.value.addEventListener('keydown', (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.code === 'KeyS') {
e.preventDefault()
save()
}
})
watchEffect(() => {
const cur = editor.getValue()
if (props.value !== cur) {
editor.setValue(props.value)
}
})
watchEffect(() => {
editor.setOption('mode', props.mode)
})
setTimeout(() => {
editor.refresh()
}, 50)
if (needAutoResize) {
window.addEventListener(
'resize',
debounce(() => {
editor.refresh()
})
)
}
})
</script>
<style>
.editor {
position: relative;
height: 100%;
width: 100%;
overflow: hidden;
}
.CodeMirror {
font-family: var(--font-code);
line-height: 1.5;
height: 100%;
}
</style>