-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
91 lines (79 loc) · 2.71 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
/**
* External dependencies
*/
import { forEach } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, forwardRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import createHigherOrderComponent from '../../utils/create-higher-order-component';
import Listener from './listener';
/**
* Listener instance responsible for managing document event handling.
*
* @type {Listener}
*/
const listener = new Listener();
/**
* Higher-order component creator which, given an object of DOM event types and
* values corresponding to a callback function name on the component, will
* create or update a window event handler to invoke the callback when an event
* occurs. On behalf of the consuming developer, the higher-order component
* manages unbinding when the component unmounts, and binding at most a single
* event handler for the entire application.
*
* @param {Object<string,string>} eventTypesToHandlers Object with keys of DOM
* event type, the value a
* name of the function on
* the original component's
* instance which handles
* the event.
*
* @return {Function} Higher-order component.
*/
function withGlobalEvents( eventTypesToHandlers ) {
return createHigherOrderComponent( ( WrappedComponent ) => {
class Wrapper extends Component {
constructor() {
super( ...arguments );
this.handleEvent = this.handleEvent.bind( this );
this.handleRef = this.handleRef.bind( this );
}
componentDidMount() {
forEach( eventTypesToHandlers, ( handler, eventType ) => {
listener.add( eventType, this );
} );
}
componentWillUnmount() {
forEach( eventTypesToHandlers, ( handler, eventType ) => {
listener.remove( eventType, this );
} );
}
handleEvent( event ) {
const handler = eventTypesToHandlers[ event.type ];
if ( typeof this.wrappedRef[ handler ] === 'function' ) {
this.wrappedRef[ handler ]( event );
}
}
handleRef( el ) {
this.wrappedRef = el;
// Any component using `withGlobalEvents` that is not setting a `ref`
// will cause `this.props.forwardedRef` to be `null`, so we need this
// check.
if ( this.props.forwardedRef ) {
this.props.forwardedRef( el );
}
}
render() {
return <WrappedComponent { ...this.props.ownProps } ref={ this.handleRef } />;
}
}
return forwardRef( ( props, ref ) => {
return <Wrapper ownProps={ props } forwardedRef={ ref } />;
} );
}, 'withGlobalEvents' );
}
export default withGlobalEvents;