/**
* Created by Zhang Haijun on 2017/9/6.
*/
<template>
  <textarea ref="textarea"></textarea>
</template>

<script>
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/rubyblue.css';
import CodeMirror from 'codemirror';

export default {
    props: {
        value: {
            type: String
        },
        readOnly: {
            type: Boolean,
            default: true
        }
    },
    data () {
        return {
            codeMirror: ''
        };
    },
    watch: {
        value (value) {
            const editorValue = this.codeMirror.getValue();
            if (value !== editorValue) { // 容错优化，防止bug产生，change事件后防止再次赋值
                this.codeMirror.setValue(value);
            }
        },
        readOnly (value) {
            this.codeMirror.setOption('readOnly', value);
        }
    },
    mounted () {
        this.codeMirror = CodeMirror.fromTextArea(this.$refs.textarea, {
            lineNumbers: true,
            theme: 'rubyblue',
            mode: 'shell',
            readOnly: this.readOnly,
            extraKeys: {
                'F11': function (cm) {
                    cm.setOption('fullScreen', !cm.getOption('fullScreen'));
                },
                'Esc': function (cm) {
                    if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
                }
            }
        });
        this.codeMirror.setValue(this.value);
        this.codeMirror.on('change', cm => {
            this.$emit('changed', cm.getValue());
        });
    },
    methods: {}
};
</script>
