<template>
  <component
    :is="tagName"
    ref="contenteditableEle"
    class="contenteditable-ele"
    :contenteditable="contenteditable"
    @input="inputChange"
    @blur="inputChange"
    @click="$emit('click', $event)"
  >
  </component>
</template>

<script setup lang="ts" name="ContentEditAble">
import { ref, onMounted, withDefaults, watch } from 'vue'
import useVModel from '@/hooks/useVModel'

defineEmits(['click'])

const props = withDefaults(
  defineProps<{
    modelValue?: string
    tagName?: string
    contenteditable?: boolean | string
    autofocus?: boolean
  }>(),
  {
    modelValue: '',
    tagName: 'div',
    contenteditable: true,
    autofocus: true,
  }
)

const contentValue = useVModel(props, 'modelValue')

const contenteditableEle = ref<HTMLElement | null>()

function updateContent(content: string) {
  if (contenteditableEle.value) {
    contenteditableEle.value.innerHTML = content
  }
}

function focus() {
  if (contenteditableEle.value) {
    contenteditableEle.value?.focus()
  }
}

function inputChange(event: Event) {
  const target = event.target as HTMLElement
  contentValue.value = target.innerHTML
}

watch(
  () => props.modelValue,
  () => {
    if (props.modelValue !== contenteditableEle.value?.innerHTML) {
      updateContent(props.modelValue ?? '')
    }
  }
)

onMounted(() => {
  updateContent(contentValue.value ?? '')
  setTimeout(() => {
    focus()
  })
})
</script>

<style scoped lang="scss"></style>
