UNPKG

52.2 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('mobx')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'react', 'mobx'], factory) :
4 (factory((global.mobxReact = {}),global.React,global.mobx));
5}(this, (function (exports,React,mobx) { 'use strict';
6
7 var React__default = 'default' in React ? React['default'] : React;
8
9 function _typeof(obj) {
10 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
11 _typeof = function (obj) {
12 return typeof obj;
13 };
14 } else {
15 _typeof = function (obj) {
16 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
17 };
18 }
19
20 return _typeof(obj);
21 }
22
23 function _classCallCheck(instance, Constructor) {
24 if (!(instance instanceof Constructor)) {
25 throw new TypeError("Cannot call a class as a function");
26 }
27 }
28
29 function _defineProperties(target, props) {
30 for (var i = 0; i < props.length; i++) {
31 var descriptor = props[i];
32 descriptor.enumerable = descriptor.enumerable || false;
33 descriptor.configurable = true;
34 if ("value" in descriptor) descriptor.writable = true;
35 Object.defineProperty(target, descriptor.key, descriptor);
36 }
37 }
38
39 function _createClass(Constructor, protoProps, staticProps) {
40 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
41 if (staticProps) _defineProperties(Constructor, staticProps);
42 return Constructor;
43 }
44
45 function _defineProperty(obj, key, value) {
46 if (key in obj) {
47 Object.defineProperty(obj, key, {
48 value: value,
49 enumerable: true,
50 configurable: true,
51 writable: true
52 });
53 } else {
54 obj[key] = value;
55 }
56
57 return obj;
58 }
59
60 function _objectSpread(target) {
61 for (var i = 1; i < arguments.length; i++) {
62 var source = arguments[i] != null ? arguments[i] : {};
63 var ownKeys = Object.keys(source);
64
65 if (typeof Object.getOwnPropertySymbols === 'function') {
66 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
67 return Object.getOwnPropertyDescriptor(source, sym).enumerable;
68 }));
69 }
70
71 ownKeys.forEach(function (key) {
72 _defineProperty(target, key, source[key]);
73 });
74 }
75
76 return target;
77 }
78
79 function _inherits(subClass, superClass) {
80 if (typeof superClass !== "function" && superClass !== null) {
81 throw new TypeError("Super expression must either be null or a function");
82 }
83
84 subClass.prototype = Object.create(superClass && superClass.prototype, {
85 constructor: {
86 value: subClass,
87 writable: true,
88 configurable: true
89 }
90 });
91 if (superClass) _setPrototypeOf(subClass, superClass);
92 }
93
94 function _getPrototypeOf(o) {
95 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
96 return o.__proto__ || Object.getPrototypeOf(o);
97 };
98 return _getPrototypeOf(o);
99 }
100
101 function _setPrototypeOf(o, p) {
102 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
103 o.__proto__ = p;
104 return o;
105 };
106
107 return _setPrototypeOf(o, p);
108 }
109
110 function _assertThisInitialized(self) {
111 if (self === void 0) {
112 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
113 }
114
115 return self;
116 }
117
118 function _possibleConstructorReturn(self, call) {
119 if (call && (typeof call === "object" || typeof call === "function")) {
120 return call;
121 }
122
123 return _assertThisInitialized(self);
124 }
125
126 // These functions can be stubbed out in specific environments
127
128 function unwrapExports (x) {
129 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
130 }
131
132 function createCommonjsModule(fn, module) {
133 return module = { exports: {} }, fn(module, module.exports), module.exports;
134 }
135
136 var reactIs_production_min = createCommonjsModule(function (module, exports) {
137 Object.defineProperty(exports,"__esModule",{value:!0});
138 var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.placeholder"):60113;
139 function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f;
140 exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&("function"===typeof a.then||a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};
141 exports.isForwardRef=function(a){return q(a)===m};exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f};
142 });
143
144 unwrapExports(reactIs_production_min);
145 var reactIs_production_min_1 = reactIs_production_min.typeOf;
146 var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
147 var reactIs_production_min_3 = reactIs_production_min.ContextConsumer;
148 var reactIs_production_min_4 = reactIs_production_min.ContextProvider;
149 var reactIs_production_min_5 = reactIs_production_min.Element;
150 var reactIs_production_min_6 = reactIs_production_min.ForwardRef;
151 var reactIs_production_min_7 = reactIs_production_min.Fragment;
152 var reactIs_production_min_8 = reactIs_production_min.Profiler;
153 var reactIs_production_min_9 = reactIs_production_min.Portal;
154 var reactIs_production_min_10 = reactIs_production_min.StrictMode;
155 var reactIs_production_min_11 = reactIs_production_min.isValidElementType;
156 var reactIs_production_min_12 = reactIs_production_min.isAsyncMode;
157 var reactIs_production_min_13 = reactIs_production_min.isContextConsumer;
158 var reactIs_production_min_14 = reactIs_production_min.isContextProvider;
159 var reactIs_production_min_15 = reactIs_production_min.isElement;
160 var reactIs_production_min_16 = reactIs_production_min.isForwardRef;
161 var reactIs_production_min_17 = reactIs_production_min.isFragment;
162 var reactIs_production_min_18 = reactIs_production_min.isProfiler;
163 var reactIs_production_min_19 = reactIs_production_min.isPortal;
164 var reactIs_production_min_20 = reactIs_production_min.isStrictMode;
165
166 var reactIs = createCommonjsModule(function (module) {
167
168 {
169 module.exports = reactIs_production_min;
170 }
171 });
172
173 var _ReactIs$ForwardRef;
174
175 function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
176
177 /**
178 * Copyright 2015, Yahoo! Inc.
179 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
180 */
181
182
183 var REACT_STATICS = {
184 childContextTypes: true,
185 contextTypes: true,
186 defaultProps: true,
187 displayName: true,
188 getDefaultProps: true,
189 getDerivedStateFromProps: true,
190 mixins: true,
191 propTypes: true,
192 type: true
193 };
194
195 var KNOWN_STATICS = {
196 name: true,
197 length: true,
198 prototype: true,
199 caller: true,
200 callee: true,
201 arguments: true,
202 arity: true
203 };
204
205 var TYPE_STATICS = _defineProperty$1({}, reactIs.ForwardRef, (_ReactIs$ForwardRef = {}, _defineProperty$1(_ReactIs$ForwardRef, '$$typeof', true), _defineProperty$1(_ReactIs$ForwardRef, 'render', true), _ReactIs$ForwardRef));
206
207 var defineProperty = Object.defineProperty;
208 var getOwnPropertyNames = Object.getOwnPropertyNames;
209 var getOwnPropertySymbols = Object.getOwnPropertySymbols;
210 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
211 var getPrototypeOf = Object.getPrototypeOf;
212 var objectPrototype = Object.prototype;
213
214 function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
215 if (typeof sourceComponent !== 'string') {
216 // don't hoist over string (html) components
217
218 if (objectPrototype) {
219 var inheritedComponent = getPrototypeOf(sourceComponent);
220 if (inheritedComponent && inheritedComponent !== objectPrototype) {
221 hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
222 }
223 }
224
225 var keys = getOwnPropertyNames(sourceComponent);
226
227 if (getOwnPropertySymbols) {
228 keys = keys.concat(getOwnPropertySymbols(sourceComponent));
229 }
230
231 var targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS;
232 var sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS;
233
234 for (var i = 0; i < keys.length; ++i) {
235 var key = keys[i];
236 if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
237 var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
238 try {
239 // Avoid failures from read-only properties
240 defineProperty(targetComponent, key, descriptor);
241 } catch (e) {}
242 }
243 }
244
245 return targetComponent;
246 }
247
248 return targetComponent;
249 }
250
251 var hoistNonReactStatics_cjs = hoistNonReactStatics;
252
253 var EventEmitter =
254 /*#__PURE__*/
255 function () {
256 function EventEmitter() {
257 _classCallCheck(this, EventEmitter);
258
259 this.listeners = [];
260 }
261
262 _createClass(EventEmitter, [{
263 key: "on",
264 value: function on(cb) {
265 var _this = this;
266
267 this.listeners.push(cb);
268 return function () {
269 var index = _this.listeners.indexOf(cb);
270
271 if (index !== -1) _this.listeners.splice(index, 1);
272 };
273 }
274 }, {
275 key: "emit",
276 value: function emit(data) {
277 this.listeners.forEach(function (fn) {
278 return fn(data);
279 });
280 }
281 }]);
282
283 return EventEmitter;
284 }();
285
286 function createChainableTypeChecker(validate) {
287 function checkType(isRequired, props, propName, componentName, location, propFullName) {
288 for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
289 rest[_key - 6] = arguments[_key];
290 }
291
292 return mobx.untracked(function () {
293 componentName = componentName || "<<anonymous>>";
294 propFullName = propFullName || propName;
295
296 if (props[propName] == null) {
297 if (isRequired) {
298 var actual = props[propName] === null ? "null" : "undefined";
299 return new Error("The " + location + " `" + propFullName + "` is marked as required " + "in `" + componentName + "`, but its value is `" + actual + "`.");
300 }
301
302 return null;
303 } else {
304 return validate.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest));
305 }
306 });
307 }
308
309 var chainedCheckType = checkType.bind(null, false);
310 chainedCheckType.isRequired = checkType.bind(null, true);
311 return chainedCheckType;
312 } // Copied from React.PropTypes
313
314
315 function isSymbol(propType, propValue) {
316 // Native Symbol.
317 if (propType === "symbol") {
318 return true;
319 } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
320
321
322 if (propValue["@@toStringTag"] === "Symbol") {
323 return true;
324 } // Fallback for non-spec compliant Symbols which are polyfilled.
325
326
327 if (typeof Symbol === "function" && propValue instanceof Symbol) {
328 return true;
329 }
330
331 return false;
332 } // Copied from React.PropTypes
333
334
335 function getPropType(propValue) {
336 var propType = _typeof(propValue);
337
338 if (Array.isArray(propValue)) {
339 return "array";
340 }
341
342 if (propValue instanceof RegExp) {
343 // Old webkits (at least until Android 4.0) return 'function' rather than
344 // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
345 // passes PropTypes.object.
346 return "object";
347 }
348
349 if (isSymbol(propType, propValue)) {
350 return "symbol";
351 }
352
353 return propType;
354 } // This handles more types than `getPropType`. Only used for error messages.
355 // Copied from React.PropTypes
356
357
358 function getPreciseType(propValue) {
359 var propType = getPropType(propValue);
360
361 if (propType === "object") {
362 if (propValue instanceof Date) {
363 return "date";
364 } else if (propValue instanceof RegExp) {
365 return "regexp";
366 }
367 }
368
369 return propType;
370 }
371
372 function createObservableTypeCheckerCreator(allowNativeType, mobxType) {
373 return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
374 return mobx.untracked(function () {
375 if (allowNativeType) {
376 if (getPropType(props[propName]) === mobxType.toLowerCase()) return null;
377 }
378
379 var mobxChecker;
380
381 switch (mobxType) {
382 case "Array":
383 mobxChecker = mobx.isObservableArray;
384 break;
385
386 case "Object":
387 mobxChecker = mobx.isObservableObject;
388 break;
389
390 case "Map":
391 mobxChecker = mobx.isObservableMap;
392 break;
393
394 default:
395 throw new Error("Unexpected mobxType: ".concat(mobxType));
396 }
397
398 var propValue = props[propName];
399
400 if (!mobxChecker(propValue)) {
401 var preciseType = getPreciseType(propValue);
402 var nativeTypeExpectationMessage = allowNativeType ? " or javascript `" + mobxType.toLowerCase() + "`" : "";
403 return new Error("Invalid prop `" + propFullName + "` of type `" + preciseType + "` supplied to" + " `" + componentName + "`, expected `mobx.Observable" + mobxType + "`" + nativeTypeExpectationMessage + ".");
404 }
405
406 return null;
407 });
408 });
409 }
410
411 function createObservableArrayOfTypeChecker(allowNativeType, typeChecker) {
412 return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
413 for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {
414 rest[_key2 - 5] = arguments[_key2];
415 }
416
417 return mobx.untracked(function () {
418 if (typeof typeChecker !== "function") {
419 return new Error("Property `" + propFullName + "` of component `" + componentName + "` has " + "invalid PropType notation.");
420 }
421
422 var error = createObservableTypeCheckerCreator(allowNativeType, "Array")(props, propName, componentName);
423 if (error instanceof Error) return error;
424 var propValue = props[propName];
425
426 for (var i = 0; i < propValue.length; i++) {
427 error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + "[" + i + "]"].concat(rest));
428 if (error instanceof Error) return error;
429 }
430
431 return null;
432 });
433 });
434 }
435
436 var observableArray = createObservableTypeCheckerCreator(false, "Array");
437 var observableArrayOf = createObservableArrayOfTypeChecker.bind(null, false);
438 var observableMap = createObservableTypeCheckerCreator(false, "Map");
439 var observableObject = createObservableTypeCheckerCreator(false, "Object");
440 var arrayOrObservableArray = createObservableTypeCheckerCreator(true, "Array");
441 var arrayOrObservableArrayOf = createObservableArrayOfTypeChecker.bind(null, true);
442 var objectOrObservableObject = createObservableTypeCheckerCreator(true, "Object");
443
444 var propTypes = /*#__PURE__*/Object.freeze({
445 observableArray: observableArray,
446 observableArrayOf: observableArrayOf,
447 observableMap: observableMap,
448 observableObject: observableObject,
449 arrayOrObservableArray: arrayOrObservableArray,
450 arrayOrObservableArrayOf: arrayOrObservableArrayOf,
451 objectOrObservableObject: objectOrObservableObject
452 });
453
454 function isStateless(component) {
455 // `function() {}` has prototype, but `() => {}` doesn't
456 // `() => {}` via Babel has prototype too.
457 return !(component.prototype && component.prototype.render);
458 }
459 var symbolId = 0;
460 function newSymbol(name) {
461 if (typeof Symbol === "function") {
462 return Symbol(name);
463 }
464
465 var symbol = "__$mobx-react ".concat(name, " (").concat(symbolId, ")");
466 symbolId++;
467 return symbol;
468 }
469 var mobxMixins = newSymbol("patchMixins");
470 var mobxPatchedDefinition = newSymbol("patchedDefinition");
471
472 function getMixins(target, methodName) {
473 var mixins = target[mobxMixins] = target[mobxMixins] || {};
474 var methodMixins = mixins[methodName] = mixins[methodName] || {};
475 methodMixins.locks = methodMixins.locks || 0;
476 methodMixins.methods = methodMixins.methods || [];
477 return methodMixins;
478 }
479
480 function wrapper(realMethod, mixins) {
481 var _this = this;
482
483 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
484 args[_key - 2] = arguments[_key];
485 }
486
487 // locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls
488 mixins.locks++;
489
490 try {
491 var retVal;
492
493 if (realMethod !== undefined && realMethod !== null) {
494 retVal = realMethod.apply(this, args);
495 }
496
497 return retVal;
498 } finally {
499 mixins.locks--;
500
501 if (mixins.locks === 0) {
502 mixins.methods.forEach(function (mx) {
503 mx.apply(_this, args);
504 });
505 }
506 }
507 }
508
509 function wrapFunction(realMethod, mixins) {
510 var fn = function fn() {
511 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
512 args[_key2] = arguments[_key2];
513 }
514
515 wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args));
516 };
517
518 return fn;
519 }
520
521 function patch(target, methodName) {
522 var mixins = getMixins(target, methodName);
523
524 for (var _len3 = arguments.length, mixinMethods = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
525 mixinMethods[_key3 - 2] = arguments[_key3];
526 }
527
528 for (var _i = 0; _i < mixinMethods.length; _i++) {
529 var mixinMethod = mixinMethods[_i];
530
531 if (mixins.methods.indexOf(mixinMethod) < 0) {
532 mixins.methods.push(mixinMethod);
533 }
534 }
535
536 var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName);
537
538 if (oldDefinition && oldDefinition[mobxPatchedDefinition]) {
539 // already patched definition, do not repatch
540 return;
541 }
542
543 var originalMethod = target[methodName];
544 var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod);
545 Object.defineProperty(target, methodName, newDefinition);
546 }
547
548 function createDefinition(target, methodName, enumerable, mixins, originalMethod) {
549 var _ref;
550
551 var wrappedFunc = wrapFunction(originalMethod, mixins);
552 return _ref = {}, _defineProperty(_ref, mobxPatchedDefinition, true), _defineProperty(_ref, "get", function get() {
553 return wrappedFunc;
554 }), _defineProperty(_ref, "set", function set(value) {
555 if (this === target) {
556 wrappedFunc = wrapFunction(value, mixins);
557 } else {
558 // when it is an instance of the prototype/a child prototype patch that particular case again separately
559 // since we need to store separate values depending on wether it is the actual instance, the prototype, etc
560 // e.g. the method for super might not be the same as the method for the prototype which might be not the same
561 // as the method for the instance
562 var newDefinition = createDefinition(this, methodName, enumerable, mixins, value);
563 Object.defineProperty(this, methodName, newDefinition);
564 }
565 }), _defineProperty(_ref, "configurable", true), _defineProperty(_ref, "enumerable", enumerable), _ref;
566 }
567
568 var injectorContextTypes = {
569 mobxStores: objectOrObservableObject
570 };
571 Object.seal(injectorContextTypes);
572 var proxiedInjectorProps = {
573 contextTypes: {
574 get: function get() {
575 return injectorContextTypes;
576 },
577 set: function set(_) {
578 console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`");
579 },
580 configurable: true,
581 enumerable: false
582 },
583 isMobxInjector: {
584 value: true,
585 writable: true,
586 configurable: true,
587 enumerable: true
588 }
589 /**
590 * Store Injection
591 */
592
593 };
594
595 function createStoreInjector(grabStoresFn, component, injectNames) {
596 var displayName = "inject-" + (component.displayName || component.name || component.constructor && component.constructor.name || "Unknown");
597 if (injectNames) displayName += "-with-" + injectNames;
598
599 var Injector =
600 /*#__PURE__*/
601 function (_Component) {
602 _inherits(Injector, _Component);
603
604 function Injector() {
605 var _getPrototypeOf2;
606
607 var _this;
608
609 _classCallCheck(this, Injector);
610
611 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
612 args[_key] = arguments[_key];
613 }
614
615 _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Injector)).call.apply(_getPrototypeOf2, [this].concat(args)));
616
617 _this.storeRef = function (instance) {
618 _this.wrappedInstance = instance;
619 };
620
621 return _this;
622 }
623
624 _createClass(Injector, [{
625 key: "render",
626 value: function render() {
627 // Optimization: it might be more efficient to apply the mapper function *outside* the render method
628 // (if the mapper is a function), that could avoid expensive(?) re-rendering of the injector component
629 // See this test: 'using a custom injector is not too reactive' in inject.js
630 var newProps = {};
631
632 for (var key in this.props) {
633 if (this.props.hasOwnProperty(key)) {
634 newProps[key] = this.props[key];
635 }
636 }
637
638 var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {};
639
640 for (var _key2 in additionalProps) {
641 newProps[_key2] = additionalProps[_key2];
642 }
643
644 if (!isStateless(component)) {
645 newProps.ref = this.storeRef;
646 }
647
648 return React.createElement(component, newProps);
649 }
650 }]);
651
652 return Injector;
653 }(React.Component); // Static fields from component should be visible on the generated Injector
654
655
656 Injector.displayName = displayName;
657 hoistNonReactStatics_cjs(Injector, component);
658 Injector.wrappedComponent = component;
659 Object.defineProperties(Injector, proxiedInjectorProps);
660 return Injector;
661 }
662
663 function grabStoresByName(storeNames) {
664 return function (baseStores, nextProps) {
665 storeNames.forEach(function (storeName) {
666 if (storeName in nextProps // prefer props over stores
667 ) return;
668 if (!(storeName in baseStores)) throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider");
669 nextProps[storeName] = baseStores[storeName];
670 });
671 return nextProps;
672 };
673 }
674 /**
675 * higher order component that injects stores to a child.
676 * takes either a varargs list of strings, which are stores read from the context,
677 * or a function that manually maps the available stores from the context to props:
678 * storesToProps(mobxStores, props, context) => newProps
679 */
680
681
682 function inject()
683 /* fn(stores, nextProps) or ...storeNames */
684 {
685 var grabStoresFn;
686
687 if (typeof arguments[0] === "function") {
688 grabStoresFn = arguments[0];
689 return function (componentClass) {
690 var injected = createStoreInjector(grabStoresFn, componentClass);
691 injected.isMobxInjector = false; // supress warning
692 // mark the Injector as observer, to make it react to expressions in `grabStoresFn`,
693 // see #111
694
695 injected = observer(injected);
696 injected.isMobxInjector = true; // restore warning
697
698 return injected;
699 };
700 } else {
701 var storeNames = [];
702
703 for (var i = 0; i < arguments.length; i++) {
704 storeNames[i] = arguments[i];
705 }
706
707 grabStoresFn = grabStoresByName(storeNames);
708 return function (componentClass) {
709 return createStoreInjector(grabStoresFn, componentClass, storeNames.join("-"));
710 };
711 }
712 }
713
714 var ReactIs = require("react-is");
715
716 var mobxAdminProperty = mobx.$mobx || "$mobx";
717 var mobxIsUnmounted = newSymbol("isUnmounted");
718 /**
719 * dev tool support
720 */
721
722 var isDevtoolsEnabled = false;
723 var isUsingStaticRendering = false;
724 var warnedAboutObserverInjectDeprecation = false; // WeakMap<Node, Object>;
725
726 var componentByNodeRegistry = typeof WeakMap !== "undefined" ? new WeakMap() : undefined;
727 var renderReporter = new EventEmitter();
728 var skipRenderKey = newSymbol("skipRender");
729 var isForcingUpdateKey = newSymbol("isForcingUpdate");
730 /**
731 * Helper to set `prop` to `this` as non-enumerable (hidden prop)
732 * @param target
733 * @param prop
734 * @param value
735 */
736
737 function setHiddenProp(target, prop, value) {
738 if (!Object.hasOwnProperty.call(target, prop)) {
739 Object.defineProperty(target, prop, {
740 enumerable: false,
741 configurable: true,
742 writable: true,
743 value: value
744 });
745 } else {
746 target[prop] = value;
747 }
748 }
749
750 function findDOMNode$1(component) {
751
752 return null;
753 }
754
755 function reportRendering(component) {
756 var node = findDOMNode$1(component);
757 if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component);
758 renderReporter.emit({
759 event: "render",
760 renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
761 totalTime: Date.now() - component.__$mobRenderStart,
762 component: component,
763 node: node
764 });
765 }
766
767 function trackComponents() {
768 if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser.");
769 if (!isDevtoolsEnabled) isDevtoolsEnabled = true;
770 }
771 function useStaticRendering(useStaticRendering) {
772 isUsingStaticRendering = useStaticRendering;
773 }
774 /**
775 * Errors reporter
776 */
777
778 var errorsReporter = new EventEmitter();
779 /**
780 * Utilities
781 */
782
783 function patch$1(target, funcName) {
784 patch(target, funcName, reactiveMixin[funcName]);
785 }
786
787 function shallowEqual(objA, objB) {
788 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
789 if (is(objA, objB)) return true;
790
791 if (_typeof(objA) !== "object" || objA === null || _typeof(objB) !== "object" || objB === null) {
792 return false;
793 }
794
795 var keysA = Object.keys(objA);
796 var keysB = Object.keys(objB);
797 if (keysA.length !== keysB.length) return false;
798
799 for (var i = 0; i < keysA.length; i++) {
800 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
801 return false;
802 }
803 }
804
805 return true;
806 }
807
808 function is(x, y) {
809 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
810 if (x === y) {
811 return x !== 0 || 1 / x === 1 / y;
812 } else {
813 return x !== x && y !== y;
814 }
815 }
816
817 function makeComponentReactive(render) {
818 var _this2 = this;
819
820 if (isUsingStaticRendering === true) return render.call(this);
821
822 function reactiveRender() {
823 var _this = this;
824
825 isRenderingPending = false;
826 var exception = undefined;
827 var rendering = undefined;
828 reaction.track(function () {
829 if (isDevtoolsEnabled) {
830 _this.__$mobRenderStart = Date.now();
831 }
832
833 try {
834 rendering = mobx._allowStateChanges(false, baseRender);
835 } catch (e) {
836 exception = e;
837 }
838
839 if (isDevtoolsEnabled) {
840 _this.__$mobRenderEnd = Date.now();
841 }
842 });
843
844 if (exception) {
845 errorsReporter.emit(exception);
846 throw exception;
847 }
848
849 return rendering;
850 } // Generate friendly name for debugging
851
852
853 var initialName = this.displayName || this.name || this.constructor && (this.constructor.displayName || this.constructor.name) || "<component>";
854 var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID || this._reactInternalInstance && this._reactInternalInstance._debugID || this._reactInternalFiber && this._reactInternalFiber._debugID;
855 /**
856 * If props are shallowly modified, react will render anyway,
857 * so atom.reportChanged() should not result in yet another re-render
858 */
859
860 setHiddenProp(this, skipRenderKey, false);
861 /**
862 * forceUpdate will re-assign this.props. We don't want that to cause a loop,
863 * so detect these changes
864 */
865
866 setHiddenProp(this, isForcingUpdateKey, false); // wire up reactive render
867
868 var baseRender = render.bind(this);
869 var isRenderingPending = false;
870 var reaction = new mobx.Reaction("".concat(initialName, "#").concat(rootNodeID, ".render()"), function () {
871 if (!isRenderingPending) {
872 // N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
873 // This unidiomatic React usage but React will correctly warn about this so we continue as usual
874 // See #85 / Pull #44
875 isRenderingPending = true;
876 if (typeof _this2.componentWillReact === "function") _this2.componentWillReact(); // TODO: wrap in action?
877
878 if (_this2[mobxIsUnmounted] !== true) {
879 // If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted
880 // TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73
881 // However, people also claim this might happen during unit tests..
882 var hasError = true;
883
884 try {
885 setHiddenProp(_this2, isForcingUpdateKey, true);
886 if (!_this2[skipRenderKey]) React.Component.prototype.forceUpdate.call(_this2);
887 hasError = false;
888 } finally {
889 setHiddenProp(_this2, isForcingUpdateKey, false);
890 if (hasError) reaction.dispose();
891 }
892 }
893 }
894 });
895 reaction.reactComponent = this;
896 reactiveRender[mobxAdminProperty] = reaction;
897 this.render = reactiveRender;
898 return reactiveRender.call(this);
899 }
900 /**
901 * ReactiveMixin
902 */
903
904
905 var reactiveMixin = {
906 componentWillUnmount: function componentWillUnmount() {
907 if (isUsingStaticRendering === true) return;
908 this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose();
909 this[mobxIsUnmounted] = true;
910
911 if (isDevtoolsEnabled) {
912 var node = findDOMNode$1(this);
913
914 if (node && componentByNodeRegistry) {
915 componentByNodeRegistry.delete(node);
916 }
917
918 renderReporter.emit({
919 event: "destroy",
920 component: this,
921 node: node
922 });
923 }
924 },
925 componentDidMount: function componentDidMount() {
926 if (isDevtoolsEnabled) {
927 reportRendering(this);
928 }
929 },
930 componentDidUpdate: function componentDidUpdate() {
931 if (isDevtoolsEnabled) {
932 reportRendering(this);
933 }
934 },
935 shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
936 if (isUsingStaticRendering) {
937 console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side.");
938 } // update on any state changes (as is the default)
939
940
941 if (this.state !== nextState) {
942 return true;
943 } // update if props are shallowly not equal, inspired by PureRenderMixin
944 // we could return just 'false' here, and avoid the `skipRender` checks etc
945 // however, it is nicer if lifecycle events are triggered like usually,
946 // so we return true here if props are shallowly modified.
947
948
949 return !shallowEqual(this.props, nextProps);
950 }
951 };
952
953 function makeObservableProp(target, propName) {
954 var valueHolderKey = newSymbol("reactProp_".concat(propName, "_valueHolder"));
955 var atomHolderKey = newSymbol("reactProp_".concat(propName, "_atomHolder"));
956
957 function getAtom() {
958 if (!this[atomHolderKey]) {
959 setHiddenProp(this, atomHolderKey, mobx.createAtom("reactive " + propName));
960 }
961
962 return this[atomHolderKey];
963 }
964
965 Object.defineProperty(target, propName, {
966 configurable: true,
967 enumerable: true,
968 get: function get() {
969 getAtom.call(this).reportObserved();
970 return this[valueHolderKey];
971 },
972 set: function set(v) {
973 if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
974 setHiddenProp(this, valueHolderKey, v);
975 setHiddenProp(this, skipRenderKey, true);
976 getAtom.call(this).reportChanged();
977 setHiddenProp(this, skipRenderKey, false);
978 } else {
979 setHiddenProp(this, valueHolderKey, v);
980 }
981 }
982 });
983 }
984 /**
985 * Observer function / decorator
986 */
987
988
989 function observer(arg1, arg2) {
990 if (typeof arg1 === "string") {
991 throw new Error("Store names should be provided as array");
992 }
993
994 if (Array.isArray(arg1)) {
995 // TODO: remove in next major
996 // component needs stores
997 if (!warnedAboutObserverInjectDeprecation) {
998 warnedAboutObserverInjectDeprecation = true;
999 console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`');
1000 }
1001
1002 if (!arg2) {
1003 // invoked as decorator
1004 return function (componentClass) {
1005 return observer(arg1, componentClass);
1006 };
1007 } else {
1008 return inject.apply(null, arg1)(observer(arg2));
1009 }
1010 }
1011
1012 var componentClass = arg1;
1013
1014 if (componentClass.isMobxInjector === true) {
1015 console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'");
1016 }
1017
1018 if (componentClass.__proto__ === React.PureComponent) {
1019 console.warn("Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together");
1020 } // Unwrap forward refs into `<Observer>` component
1021 // we need to unwrap the render, because it is the inner render that needs to be tracked,
1022 // not the ForwardRef HoC
1023
1024
1025 if (componentClass["$$typeof"] === ReactIs.ForwardRef) {
1026 var _baseRender = componentClass.render;
1027 if (typeof _baseRender !== "function") throw new Error("render property of ForwardRef was not a function");
1028 return _objectSpread({}, componentClass, {
1029 render: function render() {
1030 var _arguments = arguments;
1031 return React__default.createElement(Observer, null, function () {
1032 return _baseRender.apply(undefined, _arguments);
1033 });
1034 }
1035 });
1036 } // Stateless function component:
1037 // If it is function but doesn't seem to be a react class constructor,
1038 // wrap it to a react class automatically
1039
1040
1041 if (typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass)) {
1042 var _class, _temp;
1043
1044 var observerComponent = observer((_temp = _class =
1045 /*#__PURE__*/
1046 function (_Component) {
1047 _inherits(_class, _Component);
1048
1049 function _class() {
1050 _classCallCheck(this, _class);
1051
1052 return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
1053 }
1054
1055 _createClass(_class, [{
1056 key: "render",
1057 value: function render() {
1058 return componentClass.call(this, this.props, this.context);
1059 }
1060 }]);
1061
1062 return _class;
1063 }(React.Component), _class.displayName = componentClass.displayName || componentClass.name, _class.contextTypes = componentClass.contextTypes, _class.propTypes = componentClass.propTypes, _class.defaultProps = componentClass.defaultProps, _temp));
1064 hoistNonReactStatics_cjs(observerComponent, componentClass);
1065 return observerComponent;
1066 }
1067
1068 if (!componentClass) {
1069 throw new Error("Please pass a valid component to 'observer'");
1070 }
1071
1072 var target = componentClass.prototype || componentClass;
1073 mixinLifecycleEvents(target);
1074 componentClass.isMobXReactObserver = true;
1075 makeObservableProp(target, "props");
1076 makeObservableProp(target, "state");
1077 var baseRender = target.render;
1078
1079 target.render = function () {
1080 return makeComponentReactive.call(this, baseRender);
1081 };
1082
1083 return componentClass;
1084 }
1085
1086 function mixinLifecycleEvents(target) {
1087 ["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (funcName) {
1088 patch$1(target, funcName);
1089 });
1090
1091 if (!target.shouldComponentUpdate) {
1092 target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate;
1093 } else {
1094 if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) {
1095 // TODO: make throw in next major
1096 console.warn("Use `shouldComponentUpdate` in an `observer` based component breaks the behavior of `observer` and might lead to unexpected results. Manually implementing `sCU` should not be needed when using mobx-react.");
1097 }
1098 }
1099 }
1100
1101 var Observer = observer(function (_ref) {
1102 var children = _ref.children,
1103 observerInject = _ref.inject,
1104 render = _ref.render;
1105 var component = children || render;
1106
1107 if (typeof component === "undefined") {
1108 return null;
1109 }
1110
1111 if (!observerInject) {
1112 return component();
1113 } // TODO: remove in next major
1114
1115
1116 console.warn("<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead");
1117 var InjectComponent = inject(observerInject)(component);
1118 return React__default.createElement(InjectComponent, null);
1119 });
1120 Observer.displayName = "Observer";
1121
1122 var ObserverPropsCheck = function ObserverPropsCheck(props, key, componentName, location, propFullName) {
1123 var extraKey = key === "children" ? "render" : "children";
1124
1125 if (typeof props[key] === "function" && typeof props[extraKey] === "function") {
1126 return new Error("Invalid prop,do not use children and render in the same time in`" + componentName);
1127 }
1128
1129 if (typeof props[key] === "function" || typeof props[extraKey] === "function") {
1130 return;
1131 }
1132
1133 return new Error("Invalid prop `" + propFullName + "` of type `" + _typeof(props[key]) + "` supplied to" + " `" + componentName + "`, expected `function`.");
1134 };
1135
1136 Observer.propTypes = {
1137 render: ObserverPropsCheck,
1138 children: ObserverPropsCheck
1139 };
1140
1141 /**
1142 * Copyright (c) 2013-present, Facebook, Inc.
1143 *
1144 * This source code is licensed under the MIT license found in the
1145 * LICENSE file in the root directory of this source tree.
1146 */
1147
1148 function componentWillMount() {
1149 // Call this.constructor.gDSFP to support sub-classes.
1150 var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
1151 if (state !== null && state !== undefined) {
1152 this.setState(state);
1153 }
1154 }
1155
1156 function componentWillReceiveProps(nextProps) {
1157 // Call this.constructor.gDSFP to support sub-classes.
1158 // Use the setState() updater to ensure state isn't stale in certain edge cases.
1159 function updater(prevState) {
1160 var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
1161 return state !== null && state !== undefined ? state : null;
1162 }
1163 // Binding "this" is important for shallow renderer support.
1164 this.setState(updater.bind(this));
1165 }
1166
1167 function componentWillUpdate(nextProps, nextState) {
1168 try {
1169 var prevProps = this.props;
1170 var prevState = this.state;
1171 this.props = nextProps;
1172 this.state = nextState;
1173 this.__reactInternalSnapshotFlag = true;
1174 this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
1175 prevProps,
1176 prevState
1177 );
1178 } finally {
1179 this.props = prevProps;
1180 this.state = prevState;
1181 }
1182 }
1183
1184 // React may warn about cWM/cWRP/cWU methods being deprecated.
1185 // Add a flag to suppress these warnings for this special case.
1186 componentWillMount.__suppressDeprecationWarning = true;
1187 componentWillReceiveProps.__suppressDeprecationWarning = true;
1188 componentWillUpdate.__suppressDeprecationWarning = true;
1189
1190 function polyfill(Component) {
1191 var prototype = Component.prototype;
1192
1193 if (!prototype || !prototype.isReactComponent) {
1194 throw new Error('Can only polyfill class components');
1195 }
1196
1197 if (
1198 typeof Component.getDerivedStateFromProps !== 'function' &&
1199 typeof prototype.getSnapshotBeforeUpdate !== 'function'
1200 ) {
1201 return Component;
1202 }
1203
1204 // If new component APIs are defined, "unsafe" lifecycles won't be called.
1205 // Error if any of these lifecycles are present,
1206 // Because they would work differently between older and newer (16.3+) versions of React.
1207 var foundWillMountName = null;
1208 var foundWillReceivePropsName = null;
1209 var foundWillUpdateName = null;
1210 if (typeof prototype.componentWillMount === 'function') {
1211 foundWillMountName = 'componentWillMount';
1212 } else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
1213 foundWillMountName = 'UNSAFE_componentWillMount';
1214 }
1215 if (typeof prototype.componentWillReceiveProps === 'function') {
1216 foundWillReceivePropsName = 'componentWillReceiveProps';
1217 } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
1218 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
1219 }
1220 if (typeof prototype.componentWillUpdate === 'function') {
1221 foundWillUpdateName = 'componentWillUpdate';
1222 } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
1223 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
1224 }
1225 if (
1226 foundWillMountName !== null ||
1227 foundWillReceivePropsName !== null ||
1228 foundWillUpdateName !== null
1229 ) {
1230 var componentName = Component.displayName || Component.name;
1231 var newApiName =
1232 typeof Component.getDerivedStateFromProps === 'function'
1233 ? 'getDerivedStateFromProps()'
1234 : 'getSnapshotBeforeUpdate()';
1235
1236 throw Error(
1237 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
1238 componentName +
1239 ' uses ' +
1240 newApiName +
1241 ' but also contains the following legacy lifecycles:' +
1242 (foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
1243 (foundWillReceivePropsName !== null
1244 ? '\n ' + foundWillReceivePropsName
1245 : '') +
1246 (foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
1247 '\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
1248 'https://fb.me/react-async-component-lifecycle-hooks'
1249 );
1250 }
1251
1252 // React <= 16.2 does not support static getDerivedStateFromProps.
1253 // As a workaround, use cWM and cWRP to invoke the new static lifecycle.
1254 // Newer versions of React will ignore these lifecycles if gDSFP exists.
1255 if (typeof Component.getDerivedStateFromProps === 'function') {
1256 prototype.componentWillMount = componentWillMount;
1257 prototype.componentWillReceiveProps = componentWillReceiveProps;
1258 }
1259
1260 // React <= 16.2 does not support getSnapshotBeforeUpdate.
1261 // As a workaround, use cWU to invoke the new lifecycle.
1262 // Newer versions of React will ignore that lifecycle if gSBU exists.
1263 if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
1264 if (typeof prototype.componentDidUpdate !== 'function') {
1265 throw new Error(
1266 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
1267 );
1268 }
1269
1270 prototype.componentWillUpdate = componentWillUpdate;
1271
1272 var componentDidUpdate = prototype.componentDidUpdate;
1273
1274 prototype.componentDidUpdate = function componentDidUpdatePolyfill(
1275 prevProps,
1276 prevState,
1277 maybeSnapshot
1278 ) {
1279 // 16.3+ will not execute our will-update method;
1280 // It will pass a snapshot value to did-update though.
1281 // Older versions will require our polyfilled will-update value.
1282 // We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
1283 // Because for <= 15.x versions this might be a "prevContext" object.
1284 // We also can't just check "__reactInternalSnapshot",
1285 // Because get-snapshot might return a falsy value.
1286 // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
1287 var snapshot = this.__reactInternalSnapshotFlag
1288 ? this.__reactInternalSnapshot
1289 : maybeSnapshot;
1290
1291 componentDidUpdate.call(this, prevProps, prevState, snapshot);
1292 };
1293 }
1294
1295 return Component;
1296 }
1297
1298 var specialReactKeys = {
1299 children: true,
1300 key: true,
1301 ref: true
1302 };
1303
1304 var Provider =
1305 /*#__PURE__*/
1306 function (_Component) {
1307 _inherits(Provider, _Component);
1308
1309 function Provider(props, context) {
1310 var _this;
1311
1312 _classCallCheck(this, Provider);
1313
1314 _this = _possibleConstructorReturn(this, _getPrototypeOf(Provider).call(this, props, context));
1315 _this.state = {};
1316 copyStores(props, _this.state);
1317 return _this;
1318 }
1319
1320 _createClass(Provider, [{
1321 key: "render",
1322 value: function render() {
1323 return React.Children.only(this.props.children);
1324 }
1325 }, {
1326 key: "getChildContext",
1327 value: function getChildContext() {
1328 var stores = {}; // inherit stores
1329
1330 copyStores(this.context.mobxStores, stores); // add own stores
1331
1332 copyStores(this.props, stores);
1333 return {
1334 mobxStores: stores
1335 };
1336 }
1337 }], [{
1338 key: "getDerivedStateFromProps",
1339 value: function getDerivedStateFromProps(nextProps, prevState) {
1340 if (!nextProps) return null;
1341 if (!prevState) return nextProps; // Maybe this warning is too aggressive?
1342
1343 if (Object.keys(nextProps).filter(validStoreName).length !== Object.keys(prevState).filter(validStoreName).length) console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children");
1344 if (!nextProps.suppressChangedStoreWarning) for (var key in nextProps) {
1345 if (validStoreName(key) && prevState[key] !== nextProps[key]) console.warn("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children");
1346 }
1347 return nextProps;
1348 }
1349 }]);
1350
1351 return Provider;
1352 }(React.Component);
1353
1354 Provider.contextTypes = {
1355 mobxStores: objectOrObservableObject
1356 };
1357 Provider.childContextTypes = {
1358 mobxStores: objectOrObservableObject.isRequired
1359 };
1360
1361 function copyStores(from, to) {
1362 if (!from) return;
1363
1364 for (var key in from) {
1365 if (validStoreName(key)) to[key] = from[key];
1366 }
1367 }
1368
1369 function validStoreName(key) {
1370 return !specialReactKeys[key] && key !== "suppressChangedStoreWarning";
1371 } // TODO: kill in next major
1372
1373
1374 polyfill(Provider);
1375
1376 var storeKey = newSymbol("disposeOnUnmount");
1377
1378 function runDisposersOnWillUnmount() {
1379 var _this = this;
1380
1381 if (!this[storeKey]) {
1382 // when disposeOnUnmount is only set to some instances of a component it will still patch the prototype
1383 return;
1384 }
1385
1386 this[storeKey].forEach(function (propKeyOrFunction) {
1387 var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction;
1388
1389 if (prop !== undefined && prop !== null) {
1390 if (typeof prop !== "function") {
1391 throw new Error("[mobx-react] disposeOnUnmount only works on functions such as disposers returned by reactions, autorun, etc.");
1392 }
1393
1394 prop();
1395 }
1396 });
1397 this[storeKey] = [];
1398 }
1399
1400 function disposeOnUnmount(target, propertyKeyOrFunction) {
1401 if (Array.isArray(propertyKeyOrFunction)) {
1402 return propertyKeyOrFunction.map(function (fn) {
1403 return disposeOnUnmount(target, fn);
1404 });
1405 }
1406
1407 if (!target instanceof React.Component) {
1408 throw new Error("[mobx-react] disposeOnUnmount only works on class based React components.");
1409 }
1410
1411 if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function") {
1412 throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.");
1413 } // add property key / function we want run (disposed) to the store
1414
1415
1416 var componentWasAlreadyModified = !!target[storeKey];
1417 var store = target[storeKey] || (target[storeKey] = []);
1418 store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already
1419
1420 if (!componentWasAlreadyModified) {
1421 patch(target, "componentWillUnmount", runDisposersOnWillUnmount);
1422 } // return the disposer as is if invoked as a non decorator
1423
1424
1425 if (typeof propertyKeyOrFunction !== "string") {
1426 return propertyKeyOrFunction;
1427 }
1428 }
1429
1430 if (!React.Component) throw new Error("mobx-react requires React to be available");
1431 if (!mobx.spy) throw new Error("mobx-react requires mobx to be available");
1432 var onError = function onError(fn) {
1433 return errorsReporter.on(fn);
1434 };
1435
1436 if ((typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "undefined" ? "undefined" : _typeof(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) === "object") {
1437 var mobx$1 = {
1438 spy: mobx.spy,
1439 extras: {
1440 getDebugName: mobx.getDebugName
1441 }
1442 };
1443 var mobxReact = {
1444 renderReporter: renderReporter,
1445 componentByNodeRegistry: componentByNodeRegistry,
1446 componentByNodeRegistery: componentByNodeRegistry,
1447 trackComponents: trackComponents
1448 };
1449
1450 __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(mobxReact, mobx$1);
1451 }
1452
1453 exports.propTypes = propTypes;
1454 exports.PropTypes = propTypes;
1455 exports.onError = onError;
1456 exports.observer = observer;
1457 exports.Observer = Observer;
1458 exports.renderReporter = renderReporter;
1459 exports.componentByNodeRegistery = componentByNodeRegistry;
1460 exports.componentByNodeRegistry = componentByNodeRegistry;
1461 exports.trackComponents = trackComponents;
1462 exports.useStaticRendering = useStaticRendering;
1463 exports.Provider = Provider;
1464 exports.inject = inject;
1465 exports.disposeOnUnmount = disposeOnUnmount;
1466
1467 Object.defineProperty(exports, '__esModule', { value: true });
1468
1469})));