-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
65 lines (54 loc) · 1.42 KB
/
index.js
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
var React = require('react')
function fallbackMatchMedia (query) {
if (typeof matchMedia !== 'function') {
return null
}
return matchMedia(query)
}
function omitMatchMediaResult (matchMediaResult) {
if (!matchMediaResult) {
return null
}
return { media: matchMediaResult.media, matches: matchMediaResult.matches }
}
function useMedia (query) {
var mounted = React.useState(false)
var setMounted = mounted[1]
React.useEffect(function () {
setMounted(true)
}, [setMounted])
var result = React.useState(function () {
return omitMatchMediaResult(fallbackMatchMedia(query))
})
var setResult = result[1]
var callback = React.useCallback(function (matchMediaResult) {
return setResult(omitMatchMediaResult(matchMediaResult))
}, [setResult])
React.useEffect(
function () {
var matchMediaResult = fallbackMatchMedia(query)
callback(matchMediaResult)
if (matchMediaResult) {
matchMediaResult.addEventListener('change', callback)
}
return function () {
if (matchMediaResult) {
matchMediaResult.removeEventListener('change', callback)
}
}
},
[callback, query]
)
if (!mounted[0]) {
return null
}
return result[0]
}
function useMediaPredicate (query) {
var result = useMedia(query)
return (result && result.matches) || false
}
module.exports = {
useMedia: useMedia,
useMediaPredicate: useMediaPredicate
}