All files / src/hooks useResizeObserver.ts

75% Statements 12/16
66.66% Branches 4/6
80% Functions 4/5
75% Lines 12/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411x                           6x 4x 4x 2x     2x             2x 2x     2x     2x 2x 1x        
import React from 'react';
 
interface UseResizeObserverProps<T> {
    ref: React.RefObject<T | null | undefined> | undefined;
    onResize: () => void;
    box?: ResizeObserverBoxOptions;
}
 
/* FIXME: use the same hook from @gravity-ui/uikit */
export function useResizeObserver<T extends Element>({
    ref,
    onResize,
    box,
}: UseResizeObserverProps<T>) {
    React.useEffect(() => {
        const element = ref?.current;
        if (!element) {
            return undefined;
        }
 
        Iif (typeof window.ResizeObserver === 'undefined') {
            window.addEventListener('resize', onResize, false);
            return () => {
                window.removeEventListener('resize', onResize, false);
            };
        }
 
        const observer = new ResizeObserver((entries) => {
            Iif (!entries.length) {
                return;
            }
            onResize();
        });
 
        observer.observe(element, {box});
        return () => {
            observer.disconnect();
        };
    }, [ref, onResize, box]);
}