<template>
  <codemirror
    :model-value="modelValue"
    :placeholder="props.placeholder"
    :style="props.editorStyle"
    :disabled="props.disabled"
    :autofocus="false"
    :indent-with-tab="true"
    :tab-size="props.tabSize"
    :extensions="[javascript(), oneDark]"
    @ready="fnReady"
    @change="fnChange"
  />
</template>
<script lang="ts" setup>
import { Codemirror } from 'vue-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
import { ref, watch } from 'vue';

const emit = defineEmits(['update:value']);
const props = defineProps({
  value: {
    type: String,
    required: true,
  },
  placeholder: {
    type: String,
    default: 'input context here...',
  },
  /**是否禁止输入 */
  disabled: {
    type: Boolean,
    default: false,
  },
  editorStyle: {
    type: Object,
    default: () => ({ height: '400px !important' }),
  },
  /**缩进2空格 */
  tabSize: {
    type: Number,
    default: 2,
  },
});

// 绑定值
const modelValue = ref<string>('');

/**变更时更新绑定值 */
function fnChange(value: string, viewUpdate: any) {
  if (props.disabled) return;
  emit('update:value', value);
}

/**组件渲染后 */
function fnReady(payload: any) {
  modelValue.value = props.value;
}

/**监听是否value改变 */
watch(
  () => props.value,
  val => {
    modelValue.value = val;
  }
);
</script>

<style lang="less" scoped></style>
