-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
98 lines (82 loc) · 2.66 KB
/
Copy pathindex.js
File metadata and controls
98 lines (82 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import * as React from 'react'
const useIsMobile = (mobileScreenSize = 768, options = {}) => {
const { debounce = 0, enableOrientation = false } = options
if (
typeof window === 'undefined' ||
typeof window.matchMedia !== 'function'
) {
throw new Error('matchMedia not supported by browser!')
}
if (typeof mobileScreenSize !== 'number' || mobileScreenSize < 0) {
throw new TypeError('mobileScreenSize must be a positive number')
}
if (typeof debounce !== 'number' || debounce < 0) {
throw new TypeError('debounce must be a positive number')
}
const [isMobile, setIsMobile] = React.useState(
window.matchMedia(`(max-width: ${mobileScreenSize}px)`).matches
)
const [orientation, setOrientation] = React.useState(
enableOrientation
? window.matchMedia('(orientation: portrait)').matches
? 'portrait'
: 'landscape'
: null
)
const checkIsMobile = React.useCallback(
(event) => {
if (debounce > 0) {
const timer = setTimeout(() => {
setIsMobile(event.matches)
}, debounce)
return () => clearTimeout(timer)
}
setIsMobile(event.matches)
},
[debounce]
)
const checkOrientation = React.useCallback((event) => {
setOrientation(event.matches ? 'portrait' : 'landscape')
}, [])
React.useEffect(() => {
const mediaListener = window.matchMedia(
`(max-width: ${mobileScreenSize}px)`
)
checkIsMobile({ matches: mediaListener.matches })
try {
mediaListener.addEventListener('change', checkIsMobile)
} catch {
mediaListener.addListener(checkIsMobile)
}
let orientationCleanup
if (enableOrientation && typeof window.matchMedia === 'function') {
const orientationListener = window.matchMedia('(orientation: portrait)')
setOrientation(orientationListener.matches ? 'portrait' : 'landscape')
try {
orientationListener.addEventListener('change', checkOrientation)
} catch {
orientationListener.addListener(checkOrientation)
}
orientationCleanup = () => {
try {
orientationListener.removeEventListener('change', checkOrientation)
} catch {
orientationListener.removeListener(checkOrientation)
}
}
}
return () => {
try {
mediaListener.removeEventListener('change', checkIsMobile)
} catch {
mediaListener.removeListener(checkIsMobile)
}
if (orientationCleanup) orientationCleanup()
}
}, [mobileScreenSize, checkIsMobile, enableOrientation, checkOrientation])
if (enableOrientation) {
return { isMobile, orientation }
}
return isMobile
}
export default useIsMobile