<template>
    <div id="pattern-box" class="pattern-box-wrapper">
        <input autofocus
               v-model="pattern"
               placeholder="Enter pattern"
               class="pattern-box"
               type="text">

        <p v-show="error" class="error-text">{{ error }}</p>
    </div>
</template>

<script lang="ts">
    import {Component, Prop, Watch, Vue} from "vue-property-decorator";

    @Component
    export default class PatternBox extends Vue {
        private pattern: string = '';
        private error: string = '';

        @Prop({default: ''}) public readonly value: string = '';

        @Watch('pattern')
        patternChanged(value: string) {
            try {
                new RegExp(value);

                this.$emit('input', value);

                this.error = '';
            } catch (error) {
                this.error = 'Expression is invalid';
            }
        }

        @Watch('value')
        valueChanged(value: string) {
            this.pattern = value
        }

        created() {
            this.pattern = this.value
        }
    };
</script>
