<template>
    <div ref="editorRef" class="editor-main"></div>
</template>
<script lang="ts" setup>
import { basicSetup, EditorView } from "codemirror";
import { EditorState } from "@codemirror/state";
import { python } from '@codemirror/lang-python'
import { onMounted, ref,watch } from "vue";
const props = defineProps<{
    code: string;
}>();

const editorRef = ref();
const editorView = ref();
const initEditor = () => {
    if (editorView.value) {
        editorView.value.destroy();
    }
    const startState = EditorState.create({
        doc: props.code,
        extensions: [basicSetup, python()],
    });
    if (editorRef.value) {
        editorView.value = new EditorView({
            state: startState,
            parent: editorRef.value,
        });
    }
};

onMounted(() => {
    initEditor();
});

// 监听 props.code 变化，实时更新编辑器内容
watch(
    () => props.code,
    (newValue) => {
        if (editorView.value) {
            // 只替换文档内容，不重建整个编辑器
            editorView.value.dispatch({
                changes: {
                    from: 0,
                    to: editorView.value.state.doc.length,
                    insert: newValue,
                },
            });
        } else {
            initEditor();
        }
    }
);

</script>

<style  scoped>
.editor-main {
   max-height: 500px;
   overflow-y: auto;
}
</style>
