( ComposedComponent: ComponentType<P> )
| 55 | * ``` |
| 56 | */ |
| 57 | export function WidthProvider<P extends { width: number }>( |
| 58 | ComposedComponent: ComponentType<P> |
| 59 | ): ComponentType<WithWidthProps<P>> { |
| 60 | function WidthProviderWrapper(props: WithWidthProps<P>) { |
| 61 | const { measureBeforeMount = false, className, style, ...rest } = props; |
| 62 | |
| 63 | const [width, setWidth] = useState(1280); |
| 64 | const [mounted, setMounted] = useState(false); |
| 65 | const elementRef = useRef<HTMLDivElement>(null); |
| 66 | const resizeObserverRef = useRef<ResizeObserver | null>(null); |
| 67 | |
| 68 | // Set mounted state on first render |
| 69 | useEffect(() => { |
| 70 | setMounted(true); |
| 71 | }, []); |
| 72 | |
| 73 | // Set up ResizeObserver - re-runs when mounted changes to observe the new element |
| 74 | // This fixes measureBeforeMount where the ref changes from placeholder to composed component |
| 75 | useEffect(() => { |
| 76 | const node = elementRef.current; |
| 77 | if (!(node instanceof HTMLElement)) return; |
| 78 | |
| 79 | let rafId: number | null = null; |
| 80 | |
| 81 | const observer = new ResizeObserver(entries => { |
| 82 | if (entries[0]) { |
| 83 | const newWidth = entries[0].contentRect.width; |
| 84 | |
| 85 | // Defer state update to next paint cycle to avoid |
| 86 | // "ResizeObserver loop completed with undelivered notifications" error (#1959) |
| 87 | if (rafId !== null) { |
| 88 | cancelAnimationFrame(rafId); |
| 89 | } |
| 90 | rafId = requestAnimationFrame(() => { |
| 91 | setWidth(newWidth); |
| 92 | rafId = null; |
| 93 | }); |
| 94 | } |
| 95 | }); |
| 96 | |
| 97 | observer.observe(node); |
| 98 | resizeObserverRef.current = observer; |
| 99 | |
| 100 | return () => { |
| 101 | if (rafId !== null) { |
| 102 | cancelAnimationFrame(rafId); |
| 103 | } |
| 104 | observer.unobserve(node); |
| 105 | observer.disconnect(); |
| 106 | }; |
| 107 | }, [mounted]); |
| 108 | |
| 109 | // If measureBeforeMount is true and not yet mounted, render placeholder |
| 110 | if (measureBeforeMount && !mounted) { |
| 111 | return ( |
| 112 | <div |
| 113 | className={clsx(className, layoutClassName)} |
| 114 | style={style} |
no outgoing calls
no test coverage detected
searching dependent graphs…