<template>
    <div></div>
</template>

<script>
import { EditorView } from 'codemirror';
import { EditorState } from '@codemirror/state';
import { keymap } from '@codemirror/view';
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';

const theme = EditorView.theme({
    '&.cm-focused': {
        outline: 'none',
    },
});

export default {
    name: 'CodeEditor',

    props: {
        value: {
            type: String,
            default: '',
        },

        readOnly: {
            type: Boolean,
            default: false,
        },

        singleLine: {
            type: Boolean,
            default: false,
        },

        setup: {
            type: Array,
            default: () => [],
        },
    },

    mounted() {
        this.view = this.createEditor({ doc: this.value, parent: this.$el });
    },

    destroyed() {
        this.view.destroy();
    },

    methods: {
        createEditor({ doc, parent }) {
            const updateListener = EditorView.updateListener.of((update) => {
                if (update.docChanged && update.state.doc.toString() !== this.value) {
                    this.$emit('input', update.state.doc.toString());
                }
            });

            // if (this.singleLine) {
            //     doc = removeBr(doc);
            //     EditorState.transactionFilter.of((tr) => (tr.newDoc.lines > 1 ? [] : tr));
            // }

            return new EditorView({
                parent,
                state: EditorState.create({
                    doc,
                    extensions: [
                        this.setup,
                        updateListener,
                        theme,
                        history(),
                        EditorState.readOnly.of(this.readOnly),
                        keymap.of([...defaultKeymap, ...historyKeymap]),
                    ],
                }),
            });
        },
    },
};

// function removeBr(val) {
//     return val.replace(/[\n\r\t]+/g, ' ');
// }
</script>
