Elffuss BraidHub

kikocis/continue public

main · 1.7 KiBRawPermalink
1import { RefObject, useCallback, useEffect, useState } from "react";
2
3interface ElementSize {
4 clientWidth: number;
5 clientHeight: number;
6 scrollWidth: number;
7 scrollHeight: number;
8 isResizing: boolean;
9}
10
11interface UseElementSizeOptions {
12 debounceMs?: number;
13}
14
15export const useElementSize = (
16 ref: RefObject<HTMLElement>,
17 debounceMs = 250,
18): ElementSize => {
19 const [size, setSize] = useState<ElementSize>({
20 clientWidth: 0,
21 clientHeight: 0,
22 scrollWidth: 0,
23 scrollHeight: 0,
24 isResizing: false,
25 });
26
27 // Debounced update function
28 const debouncedSetSize = useCallback(
29 (measurements: Omit<ElementSize, "isResizing">) => {
30 let timeoutId: NodeJS.Timeout;
31
32 setSize((prev) => ({ ...prev, isResizing: true }));
33
34 timeoutId = setTimeout(() => {
35 setSize({
36 ...measurements,
37 isResizing: false,
38 });
39 }, debounceMs);
40
41 return () => clearTimeout(timeoutId);
42 },
43 [debounceMs],
44 );
45
46 useEffect(() => {
47 if (!ref.current) return;
48
49 const updateSize = () => {
50 const element = ref.current;
51 if (!element) return;
52
53 const measurements = {
54 clientWidth: element.clientWidth,
55 clientHeight: element.clientHeight,
56 scrollWidth: element.scrollWidth,
57 scrollHeight: element.scrollHeight,
58 };
59
60 debouncedSetSize(measurements);
61 };
62
63 // Create ResizeObserver instance
64 const resizeObserver = new ResizeObserver(() => {
65 updateSize();
66 });
67
68 // Start observing the element
69 resizeObserver.observe(ref.current);
70
71 // Initial size calculation
72 updateSize();
73
74 // Cleanup
75 return () => {
76 resizeObserver.disconnect();
77 };
78 }, [ref, debouncedSetSize]);
79
80 return size;
81};