<script setup lang="ts">
const inputVModel = defineModel({ type: String })
const props = defineProps<{
  placeholder?: string
}>()

watch(
  () => inputVModel.value,
  () => {
    textareaRef.value.style.height = '30px' // 重置高度
  }
)
const textareaRef = ref(null)
// 实现自适应高度（最多 4 行）
const resize = () => {
  const el = textareaRef.value
  if (!el) return

  el.style.height = 'auto' // 先清空旧高度
  const scrollHeight = el.scrollHeight

  const maxHeight = 92 // 四行时高度

  if (scrollHeight <= maxHeight) {
    el.style.overflowY = 'hidden'
    el.style.height = scrollHeight + 'px'
  } else {
    el.style.overflowY = 'auto'
    el.style.height = maxHeight + 'px'
  }
}
const emit = defineEmits(['focus', 'blur'])
</script>

<template>
  <textarea
    ref="textareaRef"
    v-model="inputVModel"
    class="input-area"
    rows="1"
    :placeholder="props.placeholder"
    @input="resize"
    @focus="emit('focus')"
    @blur="emit('blur')"
  />
</template>

<style lang="scss" scoped>
.input-area {
  width: 100%;
  font-size: 14px;
  line-height: 21px;
  padding: 4px;
  resize: none;
  overflow-y: hidden; // 默认不显示滚动条
  height: 30px; // 初始高度（1 行）
  max-height: 92px; // 最多 4 行
  box-sizing: border-box;
  border: none;
  outline-color: transparent;
  outline: none;
  background-color: transparent;
  border-radius: 8px;
  transition: height 0.1s ease;
  &::placeholder {
    color: #b5b9bf;
    opacity: 1;
  }
}
</style>
