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 width 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 width.
|
|
|
|
* @returns The current width of the element, or null if the element is not yet mounted.
|
|
|
|
*/
|
2024-07-31 23:13:36 +02:00
|
|
|
const useWidth = (ref: React.RefObject<HTMLElement>, delay = 0) => {
|
|
|
|
const [width, setWidth] = useState<number | null>(null);
|
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
const updateWidth = useCallback((entry: ResizeObserverEntry) => {
|
|
|
|
setWidth(entry.contentRect.width);
|
2024-07-31 23:13:36 +02:00
|
|
|
}, []);
|
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
const fUpdateWidth = useCallback(delay > 0 ? debounce(delay, updateWidth) : updateWidth, [updateWidth, delay]);
|
2024-07-31 23:13:36 +02:00
|
|
|
|
2024-09-04 03:43:59 +02:00
|
|
|
useResizeObserver(ref, fUpdateWidth);
|
2024-07-31 23:13:36 +02:00
|
|
|
|
|
|
|
return width;
|
|
|
|
};
|
|
|
|
|
|
|
|
export { useWidth };
|