|
| 1 | +import React, { useCallback, useEffect, useState } from "react"; |
| 2 | +import { isMobile } from "./selectors"; |
| 3 | + |
| 4 | +export function useMobileOrientation() { |
| 5 | + const [state, setState] = useState(() => { |
| 6 | + const orientation = window.innerWidth > window.innerHeight ? 90 : 0; |
| 7 | + return { |
| 8 | + isPortrait: orientation === 0, |
| 9 | + isLandscape: orientation === 90, |
| 10 | + orientation: orientation === 0 ? 'portrait' : 'landscape' |
| 11 | + } |
| 12 | + }); |
| 13 | + const handleOrientationChange = useCallback(() => { |
| 14 | + const orientation = window.innerWidth > window.innerHeight ? 90 : 0; |
| 15 | + const next = { |
| 16 | + isPortrait: orientation === 0, |
| 17 | + isLandscape: orientation === 90, |
| 18 | + orientation: orientation === 0 ? 'portrait' : 'landscape' |
| 19 | + } |
| 20 | + state.orientation !== next.orientation && setState(next); |
| 21 | + }, [state.orientation]); |
| 22 | + useEffect(() => { |
| 23 | + if (typeof window !== undefined && isMobile) { |
| 24 | + handleOrientationChange(); |
| 25 | + window.addEventListener("load", handleOrientationChange, false); |
| 26 | + window.addEventListener("resize", handleOrientationChange, false); |
| 27 | + } |
| 28 | + return () => { |
| 29 | + window.removeEventListener("resize", handleOrientationChange, false); |
| 30 | + window.removeEventListener("load", handleOrientationChange, false); |
| 31 | + } |
| 32 | + }, [handleOrientationChange]); |
| 33 | + return state; |
| 34 | +} |
| 35 | + |
| 36 | +export { useMobileOrientation }; |
0 commit comments