"use client" import React, { useMemo, useState } from "react" import { useThrottledCallback, useIsomorphicLayoutEffect } from "./external" type Dimensions = Omit const DEFAULT_STATE: Dimensions = { x: 0, y: 0, width: 0, height: 0, top: 0, left: 0, bottom: 0, right: 0, } /** * NOTE: Largely copied from https://github.com/Swizec/useDimensions/ * because we want to be able to pass in any target reference we want */ export const useDimensions = ( ref: | React.RefObject | (HTMLElement | undefined), throttleDuration = 100, ): Dimensions => { const [dimensions, setDimensions] = useState(DEFAULT_STATE) const throttledSetDimensions = useThrottledCallback( setDimensions, throttleDuration, ) const node = ref ? ("current" in ref ? ref.current : ref) : undefined const observer = useMemo( () => new ResizeObserver(() => { if (node) { const rect = node.getBoundingClientRect() throttledSetDimensions({ x: rect.x, y: rect.y, top: rect.top, left: rect.left, bottom: rect.bottom, right: rect.right, height: node.offsetHeight ?? rect.height, width: node.offsetWidth ?? rect.width, }) } }), [node, throttledSetDimensions], ) useIsomorphicLayoutEffect(() => { if (!node) { return } observer.observe(node) return () => { observer.disconnect() } }, [node]) return dimensions }