-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
101 lines (88 loc) 路 2.53 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
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
99
100
101
import {createElement, Component} from 'react';
import PropTypes from 'prop-types';
import {makeResizeAware} from 'react-resize-aware';
const contextTypes = {
queries: PropTypes.object,
width: PropTypes.number,
height: PropTypes.number,
};
class ElementQuery extends Component {
static defaultProps = {
component: 'div',
};
getChildContext() {
return {
queries: this.props.queries,
width: this.props.width,
height: this.props.height,
};
}
render() {
const {component, queries, getRef, children, proxy, ...props} = this.props;
const ref = proxy ? {getRef} : {ref: getRef};
return createElement(component, {...ref, ...props}, children);
}
static childContextTypes = contextTypes;
}
const ResizeAwareElementQuery = makeResizeAware(ElementQuery);
function matches(queries, selectors, width, height) {
const results = Object.keys(queries).map(key => {
const query = {...queries[key]};
if (query.maxWidth) {
query.maxWidth = query.maxWidth >= width;
}
if (query.minWidth) {
query.minWidth = query.minWidth <= width;
}
if (query.maxHeight) {
query.maxHeight = query.maxHeight >= height;
}
if (query.minHeight) {
query.minHeight = query.minHeight <= height;
}
return {
key,
matches: !Object.values(query).some(value => value === false),
};
});
return results.some(
({key, matches}) =>
selectors[key] !== undefined && matches === selectors[key]
);
}
class Matches extends Component {
render() {
const {queries, width, height} = this.context;
const match = matches(queries, this.props, width, height);
return match ? createElement('span', null, this.props.children) : null;
}
static contextTypes = contextTypes;
}
function makeElementQuery(component, queries) {
function Enhanced({getRef, width, height, ...props}) {
return createElement(ElementQuery, {
component,
proxy: true,
getRef,
queries,
width,
height,
matches: (...selectors) => {
const parsedSelectors = {};
selectors.forEach(arg => {
if (typeof arg === 'object') {
Object.keys(arg).forEach(key => {
parsedSelectors[key] = arg[key];
});
} else {
parsedSelectors[arg] = true;
}
});
return matches(queries, parsedSelectors, width, height);
},
...props,
});
}
return makeResizeAware(Enhanced);
}
export {ResizeAwareElementQuery as ElementQuery, Matches, makeElementQuery};