-
Notifications
You must be signed in to change notification settings - Fork 461
/
windowFocus.js
44 lines (37 loc) · 1.16 KB
/
windowFocus.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
import { windowIsFocused } from './monitor';
import React, { Component } from 'react';
function WindowFocus(options, ComposedComponent) {
return class extends Component {
constructor() {
super();
this.state = {
isWindowFocused: windowIsFocused()
};
}
componentDidMount() {
if (typeof window !== 'undefined') {
window.addEventListener('focus', this.windowFocus);
window.addEventListener('blur', this.windowBlur);
}
}
componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('focus', this.windowFocus);
window.removeEventListener('blur', this.windowBlur);
}
}
windowFocus = () => {
this.setState({ isWindowFocused: true });
};
windowBlur = () => {
this.setState({ isWindowFocused: false });
};
render() {
return <ComposedComponent isWindowFocused={this.state.isWindowFocused} {...this.props}/>;
}
}
}
export default function(...options) {
if (options.length === 1 && typeof options[0] === 'function') return WindowFocus.apply(null, [[], options[0]]);
return WindowFocus.bind(null, options);
}