From dcef11fcd36f546b5be7b113f6b9277b6c7393dd Mon Sep 17 00:00:00 2001 From: Dennis Smolek Date: Tue, 8 Oct 2024 17:35:16 +0900 Subject: [PATCH] Fix useMesasure to include safer orientation handling --- packages/fiber/src/web/use-measure.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/fiber/src/web/use-measure.ts b/packages/fiber/src/web/use-measure.ts index 8588d2f688..cc5ffef13c 100644 --- a/packages/fiber/src/web/use-measure.ts +++ b/packages/fiber/src/web/use-measure.ts @@ -131,24 +131,39 @@ export function useMeasure( state.current.resizeObserver.disconnect() state.current.resizeObserver = null } + if (state.current.orientationHandler) { - screen.orientation.removeEventListener('orientationchange', state.current.orientationHandler) + if ('orientation' in screen && 'removeEventListener' in screen.orientation) { + screen.orientation.removeEventListener('change', state.current.orientationHandler) + } else if ('onorientationchange' in window) { + window.removeEventListener('orientationchange', state.current.orientationHandler) + } } } // add scroll-listeners / observers function addListeners() { if (!state.current.element) return - state.current.resizeObserver = new ResizeObserver(scrollChange) - state.current.resizeObserver!.observe(state.current.element) + state.current.resizeObserver = new ResizeObserver(resizeChange) + state.current.resizeObserver?.observe(state.current.element) if (scroll && state.current.scrollContainers) { state.current.scrollContainers.forEach((scrollContainer) => scrollContainer.addEventListener('scroll', scrollChange, { capture: true, passive: true }), ) } + + // Handle orientation changes state.current.orientationHandler = () => { scrollChange() } + + // Use screen.orientation if available + if ('orientation' in screen && 'addEventListener' in screen.orientation) { + screen.orientation.addEventListener('change', state.current.orientationHandler) + } else if ('onorientationchange' in window) { + // Fallback to orientationchange event + window.addEventListener('orientationchange', state.current.orientationHandler) + } } // the ref we expose to the user