import { useRef, useState } from 'react';
import { debounce, isInstance } from '../utils';
/**
 * @example const [ref, resizeFunction] = useAutoResize();
 * maxHeight should be provided in pixels without units
 * minHeight should be provided in pixels without units
 * @returns * ref:: A reference for the element that the resize functionality should be applied to. [React RefObject](https://reactjs.org/docs/refs-and-the-dom.html)
 *          * resizeFunction:: The function to call to automatically resize the element.
 * element refers to auto resizable element
 */
const useAutoResize = (maxHeight, minHeightProp) => {
    const element = useRef(null);
    const [minHeight, setMinHeight] = useState(minHeightProp || 0);
    const autoResize = () => {
        let scrollHeightElement = element.current;
        let iframe;
        if (element.current && isInstance(element.current, HTMLIFrameElement)) {
            iframe = element.current;
            scrollHeightElement =
                element.current.contentDocument?.querySelector('body') ?? element.current;
        }
        if (element.current) {
            let newMinHeight = minHeight;
            if (!minHeight) {
                newMinHeight =
                    scrollHeightElement.scrollHeight +
                        (scrollHeightElement.offsetHeight - scrollHeightElement.clientHeight);
                setMinHeight(newMinHeight);
            }
            // Reset the heights to the base height so there is an overflow / or none to calculate the new height
            scrollHeightElement.style.height = `${newMinHeight}px`;
            if (maxHeight) {
                scrollHeightElement.style.overflowY =
                    scrollHeightElement.scrollHeight > maxHeight ? 'auto' : 'hidden';
                const height = `${Math.min(scrollHeightElement.scrollHeight +
                    (scrollHeightElement.offsetHeight - scrollHeightElement.clientHeight), maxHeight)}px`;
                scrollHeightElement.style.height = height;
                if (iframe)
                    iframe.style.height = height;
            }
            else {
                scrollHeightElement.style.overflowY = 'hidden';
                const height = scrollHeightElement.scrollHeight +
                    (scrollHeightElement.offsetHeight - scrollHeightElement.clientHeight);
                scrollHeightElement.style.height = `${height}px`;
                if (iframe)
                    iframe.style.height = `${height}px`;
            }
        }
    };
    const debouncedAutoResize = debounce(autoResize, 100);
    return [element, debouncedAutoResize];
};
export default useAutoResize;
//# sourceMappingURL=useAutoResize.js.map