import { useState, useLayoutEffect } from 'react'

/**
 * 监听元素尺寸变化的 Hook
 */
export function useSize(target: React.RefObject<HTMLElement | null>) {
  const [size, setSize] = useState<{ width: number; height: number } | null>(null)

  useLayoutEffect(() => {
    const element = target.current
    if (!element) {
      console.log('useSize: element is null')
      return
    }

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect
        console.log('useSize: resize', width, height)
        setSize({ width, height })
      }
    })

    resizeObserver.observe(element)

    return () => {
      resizeObserver.disconnect()
    }
  }, [target])

  return size
}
