<template>
  <Codemirror
    ref="editorRef"
    placeholder="请输入"
    style="height: 500px;"
    :model-value="modelValue"
    :tab-size="2"
    :auto-focus="true"
    :indent-with-tabs="true"
    :extensions="[
      oneDark,
      javascript(),
      json()
    ]"
    @change="handleCodeChange"
  />
</template>

<script setup lang="ts">
import { ref, defineProps, watch, defineEmits } from 'vue';
import { Codemirror } from 'vue-codemirror';
import { oneDark } from '@codemirror/theme-one-dark';
import { javascript } from '@codemirror/lang-javascript';
import { json } from '@codemirror/lang-json';
import jsBeautify from 'js-beautify';

const props = defineProps({
  code: {
    type: String,
    default: ''
  }
});
const emit = defineEmits(['update:code', 'change']);
const editorRef = ref(null);
const modelValue = ref(props.code);

watch(
  () => props.code,
  (val) => {
    modelValue.value = jsBeautify.js(val, { indent_size: 2 });
  },
  { immediate: true }
)

const handleCodeChange = (val: string) => {
  try {
    emit('update:code', val);
    emit('change', val);
  } catch (error) {
    console.error(error);
    return;
  }
}
</script>

<style scoped>

</style>