|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 BadLabs |
| 3 | + * |
| 4 | + * Use of this software is governed by the Business Source License 1.1 included in the file LICENSE.txt. |
| 5 | + * |
| 6 | + * As of the Change Date specified in that file, in accordance with the Business Source License, use of this software will be governed by the Apache License, version 2.0. |
| 7 | + */ |
| 8 | + |
| 9 | +import { useCallback, useEffect, useRef } from 'react' |
| 10 | + |
| 11 | +interface ElementSize { |
| 12 | + width: number |
| 13 | + height: number |
| 14 | +} |
| 15 | + |
| 16 | +interface UseElementResizeOptions { |
| 17 | + debounceTime?: number |
| 18 | + onResize?: (size: ElementSize) => void |
| 19 | + minChangeThreshold?: number |
| 20 | + maxUpdatesPerSecond?: number |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Hook to track element size changes with debouncing |
| 25 | + * @param options Configuration options |
| 26 | + * @returns Object with ref to attach to the element |
| 27 | + */ |
| 28 | +export function useElementResize<T extends HTMLElement = HTMLDivElement>({ |
| 29 | + debounceTime = 200, |
| 30 | + onResize, |
| 31 | + minChangeThreshold = 0.5, |
| 32 | + maxUpdatesPerSecond = 2, // Max updates per second (default: 2) |
| 33 | +}: UseElementResizeOptions = {}) { |
| 34 | + const elementRef = useRef<T>(null) |
| 35 | + const lastReportedSizeRef = useRef<ElementSize>({ width: 0, height: 0 }) |
| 36 | + const lastSizeRef = useRef<ElementSize>({ width: 0, height: 0 }) |
| 37 | + const lastUpdateTimeRef = useRef<number>(0) |
| 38 | + const isInitializedRef = useRef<boolean>(false) |
| 39 | + const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null) |
| 40 | + const isResizingRef = useRef<boolean>(false) |
| 41 | + const minUpdateIntervalMs = maxUpdatesPerSecond ? (1000 / maxUpdatesPerSecond) : 0 |
| 42 | + |
| 43 | + // This function checks if we should allow an update based on time constraints |
| 44 | + const shouldAllowUpdate = useCallback(() => { |
| 45 | + const now = Date.now() |
| 46 | + const timeSinceLastUpdate = now - lastUpdateTimeRef.current |
| 47 | + return timeSinceLastUpdate >= minUpdateIntervalMs |
| 48 | + }, [minUpdateIntervalMs]) |
| 49 | + |
| 50 | + const processSizeChange = useCallback(() => { |
| 51 | + const { width, height } = lastSizeRef.current |
| 52 | + |
| 53 | + // Only trigger if dimensions have changed significantly from the last reported size |
| 54 | + if ( |
| 55 | + !isInitializedRef.current |
| 56 | + || Math.abs(width - lastReportedSizeRef.current.width) > minChangeThreshold |
| 57 | + || Math.abs(height - lastReportedSizeRef.current.height) > minChangeThreshold |
| 58 | + ) { |
| 59 | + // Update the last reported size |
| 60 | + lastReportedSizeRef.current = { width, height } |
| 61 | + lastUpdateTimeRef.current = Date.now() |
| 62 | + isInitializedRef.current = true |
| 63 | + |
| 64 | + onResize?.({ width, height }) |
| 65 | + } |
| 66 | + |
| 67 | + isResizingRef.current = false |
| 68 | + }, [onResize, minChangeThreshold]) |
| 69 | + |
| 70 | + const handleResize = useCallback((entries: ResizeObserverEntry[]) => { |
| 71 | + if (!entries.length) |
| 72 | + return |
| 73 | + |
| 74 | + const entry = entries[entries.length - 1] // Use only the most recent entry |
| 75 | + |
| 76 | + // Extract size from the entry |
| 77 | + let width = 0 |
| 78 | + let height = 0 |
| 79 | + |
| 80 | + if (entry.borderBoxSize && entry.borderBoxSize.length > 0) { |
| 81 | + width = entry.borderBoxSize[0].inlineSize |
| 82 | + height = entry.borderBoxSize[0].blockSize |
| 83 | + } else { |
| 84 | + const rect = (entry.target as HTMLElement).getBoundingClientRect() |
| 85 | + width = rect.width |
| 86 | + height = rect.height |
| 87 | + } |
| 88 | + |
| 89 | + // Store the current size |
| 90 | + lastSizeRef.current = { width, height } |
| 91 | + |
| 92 | + // If this is the first size measurement, report immediately |
| 93 | + if (!isInitializedRef.current) { |
| 94 | + processSizeChange() |
| 95 | + return |
| 96 | + } |
| 97 | + |
| 98 | + isResizingRef.current = true |
| 99 | + |
| 100 | + // Clear any existing timeout |
| 101 | + if (debounceTimeoutRef.current) { |
| 102 | + clearTimeout(debounceTimeoutRef.current) |
| 103 | + } |
| 104 | + |
| 105 | + // If we're allowed to update now based on rate limiting, and the change is significant |
| 106 | + if (shouldAllowUpdate() |
| 107 | + && (Math.abs(width - lastReportedSizeRef.current.width) > minChangeThreshold |
| 108 | + || Math.abs(height - lastReportedSizeRef.current.height) > minChangeThreshold)) { |
| 109 | + processSizeChange() |
| 110 | + } |
| 111 | + |
| 112 | + // Always set a final timeout to ensure we capture the last size |
| 113 | + debounceTimeoutRef.current = setTimeout(() => { |
| 114 | + if (isResizingRef.current) { |
| 115 | + processSizeChange() |
| 116 | + } |
| 117 | + }, debounceTime) |
| 118 | + }, [debounceTime, processSizeChange, shouldAllowUpdate, minChangeThreshold]) |
| 119 | + |
| 120 | + useEffect(() => { |
| 121 | + const element = elementRef.current |
| 122 | + if (!element) |
| 123 | + return |
| 124 | + |
| 125 | + // Reset the initialization state |
| 126 | + isInitializedRef.current = false |
| 127 | + |
| 128 | + const resizeObserver = new ResizeObserver(handleResize) |
| 129 | + resizeObserver.observe(element) |
| 130 | + |
| 131 | + return () => { |
| 132 | + if (debounceTimeoutRef.current) { |
| 133 | + clearTimeout(debounceTimeoutRef.current) |
| 134 | + |
| 135 | + // Ensure the final size gets processed when component unmounts |
| 136 | + if (isResizingRef.current) { |
| 137 | + processSizeChange() |
| 138 | + } |
| 139 | + } |
| 140 | + resizeObserver.disconnect() |
| 141 | + } |
| 142 | + }, [handleResize, processSizeChange]) |
| 143 | + |
| 144 | + return { ref: elementRef } |
| 145 | +} |
0 commit comments