index.vue
2.77 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<template>
<div :style="cacheConfigStyle">
<div ref="el" class="go-editor-area" :style="{ width, height }"></div>
<EditorWorker></EditorWorker>
<div style="margin-left:10px;">
<n-gradient-text type="danger">
{{ errorText }}
</n-gradient-text>
</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, watch, PropType, ref, computed } from 'vue'
import { useMonacoEditor } from './index.hook'
import { EditorWorker } from './index'
const props = defineProps({
width: {
type: String as PropType<string>,
default: '100%'
},
height: {
type: String as PropType<string>,
default: '90vh'
},
language: {
type: String as PropType<string>,
default: 'typescript'
},
preComment: {
type: String as PropType<string>,
default: ''
},
modelValue: {
type: String as PropType<string>,
default: ''
},
editorOptions: {
type: Object as PropType<object>,
default: () => ({})
},
config: {
type: Boolean as PropType<boolean>,
default: false
},
})
const emits = defineEmits(['blur', 'update:modelValue'])
const { el, updateVal, getEditor, createEditor } = useMonacoEditor(props.language)
const updateMonacoVal = (_val?: string) => {
const { modelValue, preComment } = props
const val = preComment ? `${preComment}\n${_val || modelValue}` : _val || modelValue
updateVal(val)
}
onMounted(() => {
const monacoEditor = createEditor(props.editorOptions)
monacoEditor!.onDidChangeModelContent(() => {
emits('update:modelValue', monacoEditor!.getValue())
})
monacoEditor!.onDidBlurEditorText(() => {
emits('blur')
})
updateMonacoVal()
})
const errorText = ref('')
const cacheConfigStyle = computed(() => {
const configStyle = {
display:'flex',
justifyContent: 'space-between',
alignItems: 'center'
}
return props.config ? configStyle : ''
})
watch(
() => props.modelValue,
(val: string) => {
if(props.language === 'json') {
try {
const res = JSON.parse(val)
if(res) {
errorText.value = ''
}
} catch (_) {
errorText.value = 'JSON格式有误,请仔细检查!'
}
}
val !== getEditor()?.getValue() && updateMonacoVal(val)
}
)
</script>
<style lang="scss" scoped>
.go-editor-area {
position: relative;
border-radius: 4px;
overflow: hidden;
padding: 5px;
padding-left: 0;
box-sizing: border-box;
background-color: rgba(0, 0, 0, 0);
@include deep() {
.margin,
.monaco-editor,
.inputarea.ime-input {
background-color: rgba(0, 0, 0, 0);
}
.monaco-editor-background {
background-color: rgba(0, 0, 0, 0);
@include fetch-bg-color('filter-color-shallow');
}
.margin {
@include fetch-bg-color('filter-color-shallow');
}
}
}
</style>