-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathwithDirection.jsx
More file actions
79 lines (66 loc) · 2.46 KB
/
withDirection.jsx
File metadata and controls
79 lines (66 loc) · 2.46 KB
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
/* eslint-disable react/forbid-foreign-prop-types */
// This higher-order component consumes a string from React context that is
// provided by the DirectionProvider component.
// We can use this to conditionally switch layout/direction for right-to-left layouts.
import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import deepmerge from 'deepmerge';
import getComponentName from 'airbnb-prop-types/build/helpers/getComponentName';
import { CHANNEL, DIRECTIONS } from './constants';
import brcastShape from './proptypes/brcast';
import directionPropType from './proptypes/direction';
const contextTypes = {
[CHANNEL]: brcastShape,
};
export { DIRECTIONS };
// set a default direction so that a component wrapped with this HOC can be
// used even without a DirectionProvider ancestor in its react tree.
const defaultDirection = DIRECTIONS.LTR;
// export for convenience, in order for components to spread these onto their propTypes
export const withDirectionPropTypes = {
direction: directionPropType.isRequired,
};
export default function withDirection(WrappedComponent) {
class WithDirection extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
direction: context[CHANNEL] ? context[CHANNEL].getState() : defaultDirection,
};
}
componentDidMount() {
if (this.context[CHANNEL]) {
// subscribe to future direction changes
this.channelUnsubscribe = this.context[CHANNEL].subscribe((direction) => {
this.setState({ direction });
});
}
}
componentWillUnmount() {
if (this.channelUnsubscribe) {
this.channelUnsubscribe();
}
}
render() {
const { direction } = this.state;
return (
<WrappedComponent
{...this.props}
direction={direction}
/>
);
}
}
const wrappedComponentName = getComponentName(WrappedComponent) || 'Component';
WithDirection.WrappedComponent = WrappedComponent;
WithDirection.contextTypes = contextTypes;
WithDirection.displayName = `withDirection(${wrappedComponentName})`;
if (WrappedComponent.propTypes) {
WithDirection.propTypes = deepmerge({}, WrappedComponent.propTypes);
delete WithDirection.propTypes.direction;
}
if (WrappedComponent.defaultProps) {
WithDirection.defaultProps = deepmerge({}, WrappedComponent.defaultProps);
}
return hoistNonReactStatics(WithDirection, WrappedComponent);
}