2024-08-21 02:01:29 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
import useResizeObserver from "@react-hook/resize-observer";
|
|
|
|
import { useCallback, useState } from "react";
|
|
|
|
import { debounce } from "throttle-debounce";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the height of the specified element and update it when the element resizes.
|
|
|
|
* @param ref The reference to the element to observe.
|
|
|
|
* @param delay The debounce delay to use for updating the height.
|
|
|
|
* @returns The current height of the element, or null if the element is not yet mounted.
|
|
|
|
*/
|
2024-07-11 00:06:19 +02:00
|
|
|
const useHeight = (ref: React.RefObject<HTMLElement>, delay = 0) => {
|
2024-07-04 18:07:06 +02:00
|
|
|
const [height, setHeight] = useState<number | null>(null);
|
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
const updateHeight = useCallback((entry: ResizeObserverEntry) => {
|
|
|
|
setHeight(entry.contentRect.height);
|
2024-07-04 18:07:06 +02:00
|
|
|
}, []);
|
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
const fUpdateHeight = useCallback(delay > 0 ? debounce(delay, updateHeight) : updateHeight, [updateHeight, delay]);
|
2024-07-04 18:07:06 +02:00
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
useResizeObserver(ref, fUpdateHeight);
|
2024-07-04 18:07:06 +02:00
|
|
|
|
|
|
|
return height;
|
|
|
|
};
|
|
|
|
|
2024-07-11 00:06:19 +02:00
|
|
|
export { useHeight };
|