-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathuseMediaQuery.ts
85 lines (78 loc) · 1.85 KB
/
useMediaQuery.ts
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
import { useWindowDimensions } from 'react-native';
import isNil from 'lodash.isnil';
type QueryKeys =
| 'maxWidth'
| 'minWidth'
| 'maxHeight'
| 'minHeight'
| 'orientation';
type SubQuery = {
[queryKey in QueryKeys]?: number | string;
};
type Query = Array<SubQuery>;
export function useMediaQuery(query: SubQuery | Query) {
const dims = useWindowDimensions();
const height = dims?.height;
const width = dims?.width;
return iterateQuery(query, height, width);
}
function queryResolver(query: any, width?: number, height?: number) {
for (const queryKey in query) {
if (!calculateQuery(queryKey, query[queryKey], height, width)) {
return false;
}
}
return true;
}
function iterateQuery(
query: SubQuery | Query,
height?: number,
width?: number
) {
const queryResults = [];
if (Array.isArray(query)) {
query.forEach((subQuery: SubQuery) => {
queryResults.push(queryResolver(subQuery, width, height));
});
} else {
queryResults.push(queryResolver(query, width, height));
}
return queryResults;
}
function calculateQuery(
key: string,
val?: number | string,
height?: number,
width?: number
) {
let retval;
if (isNil(width) || isNil(height) || isNil(val)) {
return;
}
switch (key) {
case 'maxWidth':
retval = !isNil(val) ? width <= val : undefined;
break;
case 'minWidth':
retval = !isNil(val) ? width >= val : undefined;
break;
case 'maxHeight':
retval = !isNil(val) ? height <= val : undefined;
break;
case 'minHeight':
retval = !isNil(val) ? height >= val : undefined;
break;
case 'orientation':
if (!isNil(val)) {
if (width > height) {
retval = val === 'landscape';
} else {
retval = val === 'portrait';
}
}
break;
default:
break;
}
return retval;
}