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

<script lang="ts">
import { ref, defineComponent } 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 jsBeautifyOption = {
  "indent_size": "2",
  "indent_char": " ",
  "max_preserve_newlines": "5",
  "preserve_newlines": true,
  "keep_array_indentation": false,
  "break_chained_methods": false,
  "indent_scripts": "normal",
  "brace_style": "collapse",
  "space_before_conditional": true,
  "unescape_strings": false,
  "jslint_happy": false,
  "end_with_newline": true,
  "wrap_line_length": "0",
  "indent_inner_html": false,
  "comma_first": false,
  "e4x": false,
  "indent_empty_lines": false
}

export default defineComponent({
  name: "DEditor",
  components: { Codemirror },
  props: {
    code: {
      type: String,
      default: ''
    }
  },
  emits: ['update:code', 'change'],
  setup(props, { emit }) {
    const editorRef = ref(null);
    const modelValue = ref(jsBeautify(props.code, jsBeautifyOption));

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

<style scoped>

</style>