-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprovideContext.js
80 lines (69 loc) · 2.4 KB
/
provideContext.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
/**
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var React = require('react');
var objectAssign = require('object-assign');
var contextTypes = require('fluxible').contextTypes;
var hoistNonReactStatics = require('hoist-non-react-statics');
function createComponent(Component, customContextTypes) {
var childContextTypes = objectAssign({}, contextTypes, customContextTypes || {});
var ContextProvider = React.createClass({
displayName: 'ContextProvider',
propTypes: {
context: React.PropTypes.object.isRequired
},
childContextTypes: childContextTypes,
getChildContext: function () {
var childContext = {
executeAction: this.props.context.executeAction,
getStore: this.props.context.getStore
};
if (customContextTypes) {
Object.keys(customContextTypes).forEach(function (key) {
childContext[key] = this.props.context[key];
}, this);
}
return childContext;
},
render: function () {
return React.createElement(Component, this.props);
}
});
hoistNonReactStatics(ContextProvider, Component);
return ContextProvider;
}
/**
* Provides context prop to all children as React context
*
* Example:
* var WrappedComponent = provideContext(Component, {
* foo: React.PropTypes.string
* });
*
* Also supports the decorator pattern:
* @provideContext({
* foo: React.PropTypes.string
* })
* class ConnectedComponent extends React.Component {
* render() {
* return <div/>;
* }
* }
*
* @method provideContext
* @param {React.Component} [Component] component to wrap
* @param {object} customContextTypes Custom contextTypes to add
* @returns {React.Component} or {Function} if using decorator pattern
*/
module.exports = function provideContext(Component, customContextTypes) {
// support decorator pattern
if (arguments.length === 0 || typeof arguments[0] !== 'function') {
customContextTypes = arguments[0];
return function connectToStoresDecorator(ComponentToDecorate) {
return createComponent(ComponentToDecorate, customContextTypes);
};
}
return createComponent.apply(null, arguments);
};