|
| 1 | +import { useEffect, useRef } from "react"; |
| 2 | + |
| 3 | +export type NonNullableKeys<T> = { |
| 4 | + [P in keyof T]-?: NonNullable<T[P]>; |
| 5 | +}; |
| 6 | + |
| 7 | +export type Nullable<T> = T | null; |
| 8 | + |
| 9 | +export type ElementRect = Omit<DOMRect, "toJSON">; |
| 10 | + |
| 11 | +const initialElementRect: ElementRect = { |
| 12 | + width: 0, |
| 13 | + height: 0, |
| 14 | + y: 0, |
| 15 | + x: 0, |
| 16 | + top: 0, |
| 17 | + bottom: 0, |
| 18 | + left: 0, |
| 19 | + right: 0, |
| 20 | +}; |
| 21 | + |
| 22 | +type ResizeHandler<T extends HTMLElement> = ( |
| 23 | + elementRect: ElementRect, |
| 24 | + element: T, |
| 25 | +) => void; |
| 26 | + |
| 27 | +export const useResize = <T extends HTMLElement>( |
| 28 | + ref: Nullable<T>, |
| 29 | + onResize: ResizeHandler<T>, |
| 30 | +) => { |
| 31 | + const resizeObserverRef = useRef<ResizeObserver>(); |
| 32 | + |
| 33 | + const rectRef = useRef(initialElementRect); |
| 34 | + |
| 35 | + const didUnmount = useRef(false); |
| 36 | + |
| 37 | + useEffect(() => { |
| 38 | + didUnmount.current = false; |
| 39 | + if (ref) { |
| 40 | + resizeObserverRef.current = new ResizeObserver( |
| 41 | + (entries: ResizeObserverEntry[]) => { |
| 42 | + const newSize = ref.getBoundingClientRect(); |
| 43 | + if ( |
| 44 | + !Array.isArray(entries) || |
| 45 | + !entries.length || |
| 46 | + didUnmount.current || |
| 47 | + newSize.width === rectRef.current.width || |
| 48 | + newSize.height === rectRef.current.height |
| 49 | + ) |
| 50 | + return; |
| 51 | + |
| 52 | + onResize(newSize, ref); |
| 53 | + rectRef.current = newSize; |
| 54 | + }, |
| 55 | + ); |
| 56 | + |
| 57 | + resizeObserverRef.current?.observe(ref); |
| 58 | + } |
| 59 | + |
| 60 | + return () => { |
| 61 | + didUnmount.current = true; |
| 62 | + if (ref) { |
| 63 | + resizeObserverRef.current?.unobserve(ref); |
| 64 | + } |
| 65 | + }; |
| 66 | + }, [onResize, ref]); |
| 67 | +}; |
0 commit comments