Skip to content

fix: add orientation handling #103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 30, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type State = {
scrollContainers: HTMLOrSVGElement[] | null
resizeObserver: ResizeObserver | null
lastBounds: RectReadOnly
orientationHandler: null | (() => void)
}

export type Options = {
Expand Down Expand Up @@ -72,7 +73,13 @@ function useMeasure(
})

// keep all state in a ref
const state = useRef<State>({ element: null, scrollContainers: null, resizeObserver: null, lastBounds: bounds })
const state = useRef<State>({
element: null,
scrollContainers: null,
resizeObserver: null,
lastBounds: bounds,
orientationHandler: null,
})

// set actual debounce values early, so effects know if they should react accordingly
const scrollDebounce = debounce ? (typeof debounce === 'number' ? debounce : debounce.scroll) : null
Expand Down Expand Up @@ -129,6 +136,14 @@ function useMeasure(
state.current.resizeObserver.disconnect()
state.current.resizeObserver = null
}

if (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
Expand All @@ -141,6 +156,19 @@ function useMeasure(
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
Expand Down