UNPKG

12.9 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6
7var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
8
9var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
10
11var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
12
13exports.createContainer = createContainer;
14
15function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
16
17function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
18
19function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
20
21function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
22
23var _rx = require('rx');
24
25var _rx2 = _interopRequireDefault(_rx);
26
27var _react = require('react');
28
29var _react2 = _interopRequireDefault(_react);
30
31var _invariant = require('invariant');
32
33var _invariant2 = _interopRequireDefault(_invariant);
34
35var _debug = require('debug');
36
37var _debug2 = _interopRequireDefault(_debug);
38
39var _utils = require('./utils');
40
41var __DEV__ = process.env.NODE_ENV !== 'production';
42var debug = (0, _debug2['default'])('thundercats:container');
43var assign = Object.assign;
44
45function getChildContext(childContextTypes, currentContext) {
46
47 var compContext = assign({}, currentContext);
48 // istanbul ignore else
49 if (!childContextTypes || !childContextTypes.cat) {
50 delete compContext.cat;
51 }
52 return compContext;
53}
54
55function storeOnError(err) {
56 throw new Error('ThunderCats Store encountered an error: ' + err);
57}
58
59function storeOnCompleted() {
60 console.warn('Store has shutdown without error');
61}
62
63function verifyStore(displayName, storeName, store) {
64 /* istanbul ignore else */
65 if (__DEV__) {
66 (0, _invariant2['default'])((0, _utils.isObservable)(store) && typeof store.value === 'object', '%s should get at a store with a value but got %s for %s ' + 'with value %s', displayName, store, storeName, store && store.value);
67 }
68}
69
70function createContainer(options, Component) {
71 if (options === undefined) options = {};
72
73 /* istanbul ignore else */
74 if (!Component) {
75 return createContainer.bind(null, options);
76 }
77
78 var getPayload = typeof options.getPayload === 'function' ? options.getPayload : function () {};
79
80 /* istanbul ignore else */
81 if (__DEV__) {
82 (0, _invariant2['default'])(typeof Component === 'function', 'createContainer should get a constructor function but got %s', (0, _utils.getName)(Component) + 'Container');
83 }
84
85 var Container = (function (_React$Component) {
86 _inherits(Container, _React$Component);
87
88 function Container(props, context) {
89 var _this = this;
90
91 _classCallCheck(this, Container);
92
93 _get(Object.getPrototypeOf(Container.prototype), 'constructor', this).call(this, props, context);
94
95 /* istanbul ignore else */
96 if (__DEV__) {
97 (0, _invariant2['default'])(typeof context.cat === 'object', '%s should find an instance of the Cat in the context but got %s', (0, _utils.getName)(this), context.cat);
98 }
99
100 var cat = context.cat;
101 var val = {};
102
103 // set up observable state. This can be a single store or a combination of
104 // multiple stores
105 if (options.store) {
106 this.observableState = cat.getStore(options.store);
107 verifyStore((0, _utils.getName)(this), options.store, this.observableState);
108
109 if (typeof options.map === 'function') {
110 val = options.map(this.observableState.value);
111 this.observableState = this.observableState.map(options.map);
112 } else {
113 val = this.observableState.value;
114 }
115 } else if (options.stores) {
116 (function () {
117 var _Rx$Observable;
118
119 var storeNames = [].slice.call(options.stores);
120 var combineLatest = options.combineLatest;
121
122 /* istanbul ignore else */
123 if (__DEV__) {
124 (0, _invariant2['default'])(typeof combineLatest === 'function', '%s should get a function for options.combineLatest with ' + ' options.stores but got %s', (0, _utils.getName)(_this), combineLatest);
125 }
126
127 var stores = [];
128 var values = [];
129 storeNames.forEach(function (storeName) {
130 var store = cat.getStore(storeName);
131 verifyStore((0, _utils.getName)(_this), storeName, store);
132 stores.push(store);
133 values.push(store.value);
134 });
135
136 var args = stores.slice(0);
137 args.push(combineLatest);
138 _this.observableState = (_Rx$Observable = _rx2['default'].Observable).combineLatest.apply(_Rx$Observable, _toConsumableArray(args));
139
140 val = combineLatest.apply(undefined, values);
141 })();
142 }
143
144 /* istanbul ignore else */
145 if (__DEV__ && (options.store || options.stores)) {
146 (0, _invariant2['default'])((0, _utils.isObservable)(this.observableState), '%s should get at a store but found none for %s', (0, _utils.getName)(this), options.store || options.stores);
147 }
148
149 this.state = assign({}, val);
150
151 // set up actions on state. These will be passed down as props to child
152 if (options.actions) {
153 var actionsClassNames = Array.isArray(options.actions) ? options.actions : [options.actions];
154
155 actionsClassNames.forEach(function (name) {
156 _this.state[name] = cat.getActions(name);
157 });
158 }
159 }
160
161 _createClass(Container, [{
162 key: 'componentWillMount',
163 value: function componentWillMount() {
164 var cat = this.context.cat;
165
166 if (options.fetchAction) {
167 /* istanbul ignore else */
168 if (__DEV__) {
169 (0, _invariant2['default'])(options.fetchAction.split('.').length === 2, '%s fetch action should be in the form of ' + '`actionsClass.actionMethod` but was given %s', (0, _utils.getName)(this), options.fetchAction);
170 }
171
172 var _options$fetchAction$split = options.fetchAction.split('.');
173
174 var _options$fetchAction$split2 = _slicedToArray(_options$fetchAction$split, 2);
175
176 var fetchActionsName = _options$fetchAction$split2[0];
177 var fetchMethodName = _options$fetchAction$split2[1];
178
179 var fetchActionsInst = cat.getActions(fetchActionsName);
180 var fetchStore = undefined;
181
182 /* istanbul ignore else */
183 if (options.store) {
184 fetchStore = cat.getStore(options.store);
185 }
186
187 /* istanbul ignore else */
188 if (__DEV__) {
189 (0, _invariant2['default'])(fetchActionsInst && fetchActionsInst[fetchMethodName], '%s expected to find actions class for %s, but found %s', (0, _utils.getName)(this), options.fetchAction, fetchActionsInst);
190 }
191
192 debug('cat returned %s for %s for %s', (0, _utils.getName)(fetchActionsInst), fetchActionsName, (0, _utils.getName)(this));
193
194 var action = fetchActionsInst[fetchMethodName];
195
196 if (cat.fetchMap) {
197 debug('%s getPayload in componentWillMount', (0, _utils.getName)(this));
198 var payload = getPayload(assign({}, this.state, this.props), getChildContext(Component.contextTypes, this.context));
199
200 cat.fetchMap.set(options.fetchAction, {
201 name: options.fetchAction,
202 store: fetchStore,
203 payload: payload,
204 action: action
205 });
206 } else {
207 options.action = action;
208 }
209 }
210 if (typeof options.subscribeOnWillMount === 'function' && options.subscribeOnWillMount()) {
211 debug('%s subscribing on will mount', (0, _utils.getName)(this));
212 this.subscribeToObservableState();
213 }
214 }
215 }, {
216 key: 'componentDidMount',
217 value: function componentDidMount() {
218 this.subscribeToObservableState();
219 if (typeof options.isPrimed === 'function' && options.isPrimed(assign({}, this.state, this.props))) {
220 debug('%s store is primed, will not fetch on componentDidMount', (0, _utils.getName)(this));
221 return null;
222 }
223 /* istanbul ignore else */
224 if (options.action) {
225 debug('%s fetching on componentDidMount', (0, _utils.getName)(this));
226 options.action(getPayload(assign({}, this.state, this.props), getChildContext(Component.contextTypes, this.context)));
227 }
228 }
229 }, {
230 key: 'componentWillReceiveProps',
231 value: function componentWillReceiveProps(nextProps, nextContext) {
232 /* istanbul ignore else */
233 if (options.action && options.shouldContainerFetch && options.shouldContainerFetch(assign({}, this.state, this.props), assign({}, this.state, nextProps), this.context, nextContext)) {
234 debug('%s fetching on componentWillReceiveProps', (0, _utils.getName)(this));
235 options.action(getPayload(assign({}, this.state, nextProps), getChildContext(Component.contextTypes, nextContext)));
236 }
237 }
238 }, {
239 key: 'componentWillUnmount',
240 value: function componentWillUnmount() {
241 /* istanbul ignore else */
242 if (this.stateSubscription) {
243 debug('%s disposing store subscription', (0, _utils.getName)(this));
244 this.stateSubscription.dispose();
245 this.stateSubscription = null;
246 }
247 }
248 }, {
249 key: 'subscribeToObservableState',
250 value: function subscribeToObservableState() {
251 /* istanbul ignore else */
252 if (this.observableState && !this.stateSubscription) {
253 // Now that the component has mounted, we will use a long lived
254 // subscription
255 this.stateSubscription = this.observableState.subscribe(this.storeOnNext.bind(this), options.storeOnError || storeOnError, options.onCompleted || storeOnCompleted);
256 }
257 }
258 }, {
259 key: 'storeOnNext',
260 value: function storeOnNext(val) {
261 debug('%s value updating', (0, _utils.getName)(this), val);
262 this.setState(val);
263 }
264 }, {
265 key: 'render',
266 value: function render() {
267 return _react2['default'].createElement(Component, assign({}, this.state, this.props));
268 }
269 }], [{
270 key: 'contextTypes',
271 value: assign({}, Component.contextTypes || {}, { cat: _react.PropTypes.object.isRequired }),
272 enumerable: true
273 }, {
274 key: 'displayName',
275 value: Component.displayName + 'Container',
276 enumerable: true
277 }, {
278 key: 'propTypes',
279 value: Component.propTypes || {},
280 enumerable: true
281 }]);
282
283 return Container;
284 })(_react2['default'].Component);
285
286 return Container;
287}
288
289var contain = createContainer;
290exports.contain = contain;
\No newline at end of file