<script setup>

import {ref} from "vue"
import TInputText from "@/components/ui/TInputText.vue";
import TInputGroup from "@/components/ui/TInputGroup.vue";
import TInputGroupAddon from "@/components/ui/TInputGroupAddon.vue";

const props = defineProps(["placeholder", "width"])

const valueRef = ref()
const emits = defineEmits(["input", "change"])

const {realWidth, realValue} = (function () {
	let width = props.width
	if (width == null) {
		width = "14em"
	}
	return {
		realWidth: ref(width),
		realValue: ref("")
	}
})()

const onInput = function () {
	emits("input", {value: realValue.value})
	emits("change", {value: realValue.value})
}

const clearValue = function () {
	realValue.value = ""
	focus()
	onInput()
}

const focus = function () {
	valueRef.value.focus()
}

defineExpose({
	focus
})

</script>

<template>
	<div>
		<TInputGroup>
			<TInputText type="text" :placeholder="placeholder" :style="{width: realWidth}" @input="onInput" v-model="realValue" ref="valueRef"/>
			<TInputGroupAddon v-if="realValue.length > 0">
				<a href="" @click.prevent="clearValue"><i class="icon remove"></i></a>
			</TInputGroupAddon>
		</TInputGroup>
	</div>
</template>

<style scoped>
</style>
