<script lang="ts" setup>
import type { Options } from 'typeit'
import TypeIt from 'typeit'
import { onMounted, onUnmounted, ref, watch } from 'vue'

const props = defineProps<{
  text?: string
}>()

const textRef = ref<HTMLElement>()
let typeItInstance: any = null

function init() {
  if (!textRef.value)
    return
  if (typeItInstance) {
    typeItInstance.destroy()
  }

  // 清空上一次的内容，避免重复累加显示
  if (textRef.value) {
    textRef.value.textContent = ''
  }

  const options: Options = {
    strings: props.text || '',
    lifeLike: true,
    speed: 100,
    loop: false,
    cursor: false,
  }

  typeItInstance = new TypeIt(textRef.value, options).go()
}

onMounted(() => {
  init()
})

watch(() => props.text, () => {
  init()
})

onUnmounted(() => {
  if (typeItInstance) {
    typeItInstance.destroy()
  }
})
</script>

<template>
  <span ref="textRef" class="text-lg text-gray-800 font-bold" />
</template>
