import { defineComponent, onMounted, onUnmounted, ref } from 'vue'

// 特定比例显示矩形
export default defineComponent({
  props: {
    ratio: {
      type: Number,
      default: 1
    }
  },
  setup(props, ctx) {
    let dom: HTMLDivElement | null = null
    const height = ref(0)
    onMounted(() => {
      if (!dom) return
      const handle = () => {
        if (!dom) return
        const { width } = dom.getBoundingClientRect()
        height.value = width * props.ratio
      }
      const listen = new ResizeObserver(handle)
      handle()
      listen.observe(dom)
      onUnmounted(() => {
        listen.disconnect()
      })
    })
    return () => (
      <div
        ref={(el) => (dom = el as any)}
        class="w-full relative"
        style={{
          paddingBottom: height.value + 'px'
        }}
      >
        <div class="absolute left-0 top-0 w-full h-full">{ctx.slots.default?.()}</div>
      </div>
    )
  }
})
