<template>
    <form
        class="search"
        @submit.prevent="search"
    >
        <input
            ref="search"
            v-model="query"
            type="search"
            class="search-input"
            placeholder="Search..."
        >
        <button
            type="submit"
            class="search-button"
        ><Icon
            icon="search"
        /></button>
    </form>
</template>

<script>
async function search() {
    this.$router.push({ name: 'search', query: { q: this.query } });
    this.$emit('search');
}

function searching(to) {
    if (to) {
        setTimeout(() => {
            // nextTick does not seem to work
            this.$refs.search.focus();
        }, 20);
    }
}

export default {
    props: {
        searching: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            query: this.$route.query ? this.$route.query.q : null,
        };
    },
    watch: {
        searching,
    },
    methods: {
        search,
    },
};
</script>

<style lang="scss" scoped>
@import 'theme';

.search {
    height: 100%;
    max-width: 20rem;
    display: flex;
    flex-grow: 1;
    align-items: center;
    justify-content: flex-end;
    padding: 0 1rem 0 0;
    border-left: solid 1px $shadow-hint;

    &.compact {
        padding: 0;
        border: none;

        .search-input {
            border: solid 1px $shadow-hint;
        }

        .search-button {
            padding: 0 .5rem 0 1rem;
            margin: 0;
        }
    }
}

.search-input {
    height: 100%;
    width: 100%;
    padding: .5rem;
    border: none;
    outline: none;
    font-size: 1rem;
    outline: none;

    &::placeholder {
        color: $shadow;
    }

    &::-webkit-search-cancel-button {
        -webkit-appearance: none;
        padding: .5rem;
        position: relative;
        right: 0;
        color: $text;
        background: url('/img/cancel-circle2.svg');
        opacity: .25;

        &:hover {
            opacity: .5;
            cursor: pointer;
        }
    }

    &:focus::placeholder {
        color: $shadow-weak;
    }
}

.search-button {
    height: 100%;
    padding: 0 1rem;
    background: none;
    border: none;
    margin: .3rem 0 0 0;
    outline: none;

    .icon {
        fill: $shadow-weak;
    }

    &:hover {
        cursor: pointer;

        .icon {
            fill: $shadow;
        }
    }
}
</style>
