overleaf/services/web/frontend/js/shared/hooks/use-resize-observer.ts
Alf Eaton 85fbded781 Improve the Rich Text toolbar (#11616)
GitOrigin-RevId: d1999be629ac048058ffd82004865728796a3feb
2023-02-07 09:04:39 +00:00

39 lines
953 B
TypeScript

import { useCallback, useEffect, useRef } from 'react'
export const useResizeObserver = (handleResize: (element: Element) => void) => {
const resizeRef = useRef<{
element: Element
observer: ResizeObserver
} | null>(null)
const elementRef = useCallback(
(element: Element | null) => {
if (element && 'ResizeObserver' in window) {
if (resizeRef.current) {
resizeRef.current.observer.unobserve(resizeRef.current.element)
}
const observer = new ResizeObserver(([entry]) => {
handleResize(entry.target)
})
resizeRef.current = { element, observer }
observer.observe(element)
handleResize(element) // trigger the callback once
}
},
[handleResize]
)
useEffect(() => {
return () => {
if (resizeRef.current) {
resizeRef.current.observer.unobserve(resizeRef.current.element)
}
}
}, [])
return elementRef
}