多维表格
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

118 lines
2.6 KiB

<script setup lang="ts">
import * as monaco from 'monaco-editor'
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import TypescriptWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import { onMounted } from '#imports'
import { deepCompare } from '~/utils'
interface Props {
modelValue: any
hideMinimap?: boolean
}
interface Emits {
(event: 'update:modelValue', model: any): void
(event: 'validationError', error: any): void
(event: 'valueChanged'): void
}
const props = defineProps<Props>()
const emits = defineEmits<Emits>()
const { hideMinimap } = props
let vModel = $(useVModel(props, 'modelValue', emits))
const isValid = ref(true)
/**
* Adding monaco editor to Vite
*
* @ts-expect-error */
self.MonacoEnvironment = {
getWorker(_: any, label: string) {
switch (label) {
case 'json':
return new JsonWorker()
case 'typescript':
return new TypescriptWorker()
default:
return new EditorWorker()
}
},
}
const root = ref<HTMLDivElement>()
let editor: monaco.editor.IStandaloneCodeEditor
const format = () => {
editor.setValue(JSON.stringify(JSON.parse(editor?.getValue() as string), null, 2))
}
defineExpose({
format,
isValid,
})
onMounted(() => {
if (root.value) {
const model = monaco.editor.createModel(JSON.stringify(vModel, null, 2), 'json')
// configure the JSON language support with schemas and schema associations
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
})
editor = monaco.editor.create(root.value, {
model,
theme: 'vs',
foldingStrategy: 'indentation',
selectOnLineNumbers: true,
scrollbar: {
verticalScrollbarSize: 8,
horizontalScrollbarSize: 8,
},
tabSize: 2,
automaticLayout: true,
minimap: {
enabled: !hideMinimap,
},
})
editor.onDidChangeModelContent(async (e) => {
try {
isValid.value = true
const obj = JSON.parse(editor.getValue())
emits('valueChanged')
if (!deepCompare(vModel, obj)) vModel = obj
} catch (e) {
isValid.value = false
emits('validationError', e)
console.log(e)
}
})
}
})
watch(
() => vModel,
(v) => {
if (!editor || !v) {
return
}
try {
if (!deepCompare(v, JSON.parse(editor?.getValue() as string))) {
editor.setValue(JSON.stringify(v, null, 2))
}
} catch (e) {
editor.setValue(JSON.stringify(v, null, 2))
}
},
)
</script>
<template>
<div ref="root"></div>
</template>