UNPKG

52.7 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('mobx'), require('react-dom')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'react', 'mobx', 'react-dom'], factory) :
4 (factory((global.mobxReact = {}),global.React,global.mobx,global.ReactDOM));
5}(this, (function (exports,React,mobx,reactDom) { '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 if (reactDom.findDOMNode) {
752 try {
753 return reactDom.findDOMNode(component);
754 } catch (e) {
755 // findDOMNode will throw in react-test-renderer, see:
756 // See https://github.com/mobxjs/mobx-react/issues/216
757 // Is there a better heuristic?
758 return null;
759 }
760 }
761
762 return null;
763 }
764
765 function reportRendering(component) {
766 var node = findDOMNode$1(component);
767 if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component);
768 renderReporter.emit({
769 event: "render",
770 renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
771 totalTime: Date.now() - component.__$mobRenderStart,
772 component: component,
773 node: node
774 });
775 }
776
777 function trackComponents() {
778 if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser.");
779 if (!isDevtoolsEnabled) isDevtoolsEnabled = true;
780 }
781 function useStaticRendering(useStaticRendering) {
782 isUsingStaticRendering = useStaticRendering;
783 }
784 /**
785 * Errors reporter
786 */
787
788 var errorsReporter = new EventEmitter();
789 /**
790 * Utilities
791 */
792
793 function patch$1(target, funcName) {
794 patch(target, funcName, reactiveMixin[funcName]);
795 }
796
797 function shallowEqual(objA, objB) {
798 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
799 if (is(objA, objB)) return true;
800
801 if (_typeof(objA) !== "object" || objA === null || _typeof(objB) !== "object" || objB === null) {
802 return false;
803 }
804
805 var keysA = Object.keys(objA);
806 var keysB = Object.keys(objB);
807 if (keysA.length !== keysB.length) return false;
808
809 for (var i = 0; i < keysA.length; i++) {
810 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
811 return false;
812 }
813 }
814
815 return true;
816 }
817
818 function is(x, y) {
819 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
820 if (x === y) {
821 return x !== 0 || 1 / x === 1 / y;
822 } else {
823 return x !== x && y !== y;
824 }
825 }
826
827 function makeComponentReactive(render) {
828 var _this2 = this;
829
830 if (isUsingStaticRendering === true) return render.call(this);
831
832 function reactiveRender() {
833 var _this = this;
834
835 isRenderingPending = false;
836 var exception = undefined;
837 var rendering = undefined;
838 reaction.track(function () {
839 if (isDevtoolsEnabled) {
840 _this.__$mobRenderStart = Date.now();
841 }
842
843 try {
844 rendering = mobx._allowStateChanges(false, baseRender);
845 } catch (e) {
846 exception = e;
847 }
848
849 if (isDevtoolsEnabled) {
850 _this.__$mobRenderEnd = Date.now();
851 }
852 });
853
854 if (exception) {
855 errorsReporter.emit(exception);
856 throw exception;
857 }
858
859 return rendering;
860 } // Generate friendly name for debugging
861
862
863 var initialName = this.displayName || this.name || this.constructor && (this.constructor.displayName || this.constructor.name) || "<component>";
864 var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID || this._reactInternalInstance && this._reactInternalInstance._debugID || this._reactInternalFiber && this._reactInternalFiber._debugID;
865 /**
866 * If props are shallowly modified, react will render anyway,
867 * so atom.reportChanged() should not result in yet another re-render
868 */
869
870 setHiddenProp(this, skipRenderKey, false);
871 /**
872 * forceUpdate will re-assign this.props. We don't want that to cause a loop,
873 * so detect these changes
874 */
875
876 setHiddenProp(this, isForcingUpdateKey, false); // wire up reactive render
877
878 var baseRender = render.bind(this);
879 var isRenderingPending = false;
880 var reaction = new mobx.Reaction("".concat(initialName, "#").concat(rootNodeID, ".render()"), function () {
881 if (!isRenderingPending) {
882 // N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
883 // This unidiomatic React usage but React will correctly warn about this so we continue as usual
884 // See #85 / Pull #44
885 isRenderingPending = true;
886 if (typeof _this2.componentWillReact === "function") _this2.componentWillReact(); // TODO: wrap in action?
887
888 if (_this2[mobxIsUnmounted] !== true) {
889 // If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted
890 // TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73
891 // However, people also claim this might happen during unit tests..
892 var hasError = true;
893
894 try {
895 setHiddenProp(_this2, isForcingUpdateKey, true);
896 if (!_this2[skipRenderKey]) React.Component.prototype.forceUpdate.call(_this2);
897 hasError = false;
898 } finally {
899 setHiddenProp(_this2, isForcingUpdateKey, false);
900 if (hasError) reaction.dispose();
901 }
902 }
903 }
904 });
905 reaction.reactComponent = this;
906 reactiveRender[mobxAdminProperty] = reaction;
907 this.render = reactiveRender;
908 return reactiveRender.call(this);
909 }
910 /**
911 * ReactiveMixin
912 */
913
914
915 var reactiveMixin = {
916 componentWillUnmount: function componentWillUnmount() {
917 if (isUsingStaticRendering === true) return;
918 this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose();
919 this[mobxIsUnmounted] = true;
920
921 if (isDevtoolsEnabled) {
922 var node = findDOMNode$1(this);
923
924 if (node && componentByNodeRegistry) {
925 componentByNodeRegistry.delete(node);
926 }
927
928 renderReporter.emit({
929 event: "destroy",
930 component: this,
931 node: node
932 });
933 }
934 },
935 componentDidMount: function componentDidMount() {
936 if (isDevtoolsEnabled) {
937 reportRendering(this);
938 }
939 },
940 componentDidUpdate: function componentDidUpdate() {
941 if (isDevtoolsEnabled) {
942 reportRendering(this);
943 }
944 },
945 shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
946 if (isUsingStaticRendering) {
947 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.");
948 } // update on any state changes (as is the default)
949
950
951 if (this.state !== nextState) {
952 return true;
953 } // update if props are shallowly not equal, inspired by PureRenderMixin
954 // we could return just 'false' here, and avoid the `skipRender` checks etc
955 // however, it is nicer if lifecycle events are triggered like usually,
956 // so we return true here if props are shallowly modified.
957
958
959 return !shallowEqual(this.props, nextProps);
960 }
961 };
962
963 function makeObservableProp(target, propName) {
964 var valueHolderKey = newSymbol("reactProp_".concat(propName, "_valueHolder"));
965 var atomHolderKey = newSymbol("reactProp_".concat(propName, "_atomHolder"));
966
967 function getAtom() {
968 if (!this[atomHolderKey]) {
969 setHiddenProp(this, atomHolderKey, mobx.createAtom("reactive " + propName));
970 }
971
972 return this[atomHolderKey];
973 }
974
975 Object.defineProperty(target, propName, {
976 configurable: true,
977 enumerable: true,
978 get: function get() {
979 getAtom.call(this).reportObserved();
980 return this[valueHolderKey];
981 },
982 set: function set(v) {
983 if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
984 setHiddenProp(this, valueHolderKey, v);
985 setHiddenProp(this, skipRenderKey, true);
986 getAtom.call(this).reportChanged();
987 setHiddenProp(this, skipRenderKey, false);
988 } else {
989 setHiddenProp(this, valueHolderKey, v);
990 }
991 }
992 });
993 }
994 /**
995 * Observer function / decorator
996 */
997
998
999 function observer(arg1, arg2) {
1000 if (typeof arg1 === "string") {
1001 throw new Error("Store names should be provided as array");
1002 }
1003
1004 if (Array.isArray(arg1)) {
1005 // TODO: remove in next major
1006 // component needs stores
1007 if (!warnedAboutObserverInjectDeprecation) {
1008 warnedAboutObserverInjectDeprecation = true;
1009 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`');
1010 }
1011
1012 if (!arg2) {
1013 // invoked as decorator
1014 return function (componentClass) {
1015 return observer(arg1, componentClass);
1016 };
1017 } else {
1018 return inject.apply(null, arg1)(observer(arg2));
1019 }
1020 }
1021
1022 var componentClass = arg1;
1023
1024 if (componentClass.isMobxInjector === true) {
1025 console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'");
1026 }
1027
1028 if (componentClass.__proto__ === React.PureComponent) {
1029 console.warn("Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together");
1030 } // Unwrap forward refs into `<Observer>` component
1031 // we need to unwrap the render, because it is the inner render that needs to be tracked,
1032 // not the ForwardRef HoC
1033
1034
1035 if (componentClass["$$typeof"] === ReactIs.ForwardRef) {
1036 var _baseRender = componentClass.render;
1037 if (typeof _baseRender !== "function") throw new Error("render property of ForwardRef was not a function");
1038 return _objectSpread({}, componentClass, {
1039 render: function render() {
1040 var _arguments = arguments;
1041 return React__default.createElement(Observer, null, function () {
1042 return _baseRender.apply(undefined, _arguments);
1043 });
1044 }
1045 });
1046 } // Stateless function component:
1047 // If it is function but doesn't seem to be a react class constructor,
1048 // wrap it to a react class automatically
1049
1050
1051 if (typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass)) {
1052 var _class, _temp;
1053
1054 var observerComponent = observer((_temp = _class =
1055 /*#__PURE__*/
1056 function (_Component) {
1057 _inherits(_class, _Component);
1058
1059 function _class() {
1060 _classCallCheck(this, _class);
1061
1062 return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
1063 }
1064
1065 _createClass(_class, [{
1066 key: "render",
1067 value: function render() {
1068 return componentClass.call(this, this.props, this.context);
1069 }
1070 }]);
1071
1072 return _class;
1073 }(React.Component), _class.displayName = componentClass.displayName || componentClass.name, _class.contextTypes = componentClass.contextTypes, _class.propTypes = componentClass.propTypes, _class.defaultProps = componentClass.defaultProps, _temp));
1074 hoistNonReactStatics_cjs(observerComponent, componentClass);
1075 return observerComponent;
1076 }
1077
1078 if (!componentClass) {
1079 throw new Error("Please pass a valid component to 'observer'");
1080 }
1081
1082 var target = componentClass.prototype || componentClass;
1083 mixinLifecycleEvents(target);
1084 componentClass.isMobXReactObserver = true;
1085 makeObservableProp(target, "props");
1086 makeObservableProp(target, "state");
1087 var baseRender = target.render;
1088
1089 target.render = function () {
1090 return makeComponentReactive.call(this, baseRender);
1091 };
1092
1093 return componentClass;
1094 }
1095
1096 function mixinLifecycleEvents(target) {
1097 ["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (funcName) {
1098 patch$1(target, funcName);
1099 });
1100
1101 if (!target.shouldComponentUpdate) {
1102 target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate;
1103 } else {
1104 if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) {
1105 // TODO: make throw in next major
1106 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.");
1107 }
1108 }
1109 }
1110
1111 var Observer = observer(function (_ref) {
1112 var children = _ref.children,
1113 observerInject = _ref.inject,
1114 render = _ref.render;
1115 var component = children || render;
1116
1117 if (typeof component === "undefined") {
1118 return null;
1119 }
1120
1121 if (!observerInject) {
1122 return component();
1123 } // TODO: remove in next major
1124
1125
1126 console.warn("<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead");
1127 var InjectComponent = inject(observerInject)(component);
1128 return React__default.createElement(InjectComponent, null);
1129 });
1130 Observer.displayName = "Observer";
1131
1132 var ObserverPropsCheck = function ObserverPropsCheck(props, key, componentName, location, propFullName) {
1133 var extraKey = key === "children" ? "render" : "children";
1134
1135 if (typeof props[key] === "function" && typeof props[extraKey] === "function") {
1136 return new Error("Invalid prop,do not use children and render in the same time in`" + componentName);
1137 }
1138
1139 if (typeof props[key] === "function" || typeof props[extraKey] === "function") {
1140 return;
1141 }
1142
1143 return new Error("Invalid prop `" + propFullName + "` of type `" + _typeof(props[key]) + "` supplied to" + " `" + componentName + "`, expected `function`.");
1144 };
1145
1146 Observer.propTypes = {
1147 render: ObserverPropsCheck,
1148 children: ObserverPropsCheck
1149 };
1150
1151 /**
1152 * Copyright (c) 2013-present, Facebook, Inc.
1153 *
1154 * This source code is licensed under the MIT license found in the
1155 * LICENSE file in the root directory of this source tree.
1156 */
1157
1158 function componentWillMount() {
1159 // Call this.constructor.gDSFP to support sub-classes.
1160 var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
1161 if (state !== null && state !== undefined) {
1162 this.setState(state);
1163 }
1164 }
1165
1166 function componentWillReceiveProps(nextProps) {
1167 // Call this.constructor.gDSFP to support sub-classes.
1168 // Use the setState() updater to ensure state isn't stale in certain edge cases.
1169 function updater(prevState) {
1170 var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
1171 return state !== null && state !== undefined ? state : null;
1172 }
1173 // Binding "this" is important for shallow renderer support.
1174 this.setState(updater.bind(this));
1175 }
1176
1177 function componentWillUpdate(nextProps, nextState) {
1178 try {
1179 var prevProps = this.props;
1180 var prevState = this.state;
1181 this.props = nextProps;
1182 this.state = nextState;
1183 this.__reactInternalSnapshotFlag = true;
1184 this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
1185 prevProps,
1186 prevState
1187 );
1188 } finally {
1189 this.props = prevProps;
1190 this.state = prevState;
1191 }
1192 }
1193
1194 // React may warn about cWM/cWRP/cWU methods being deprecated.
1195 // Add a flag to suppress these warnings for this special case.
1196 componentWillMount.__suppressDeprecationWarning = true;
1197 componentWillReceiveProps.__suppressDeprecationWarning = true;
1198 componentWillUpdate.__suppressDeprecationWarning = true;
1199
1200 function polyfill(Component) {
1201 var prototype = Component.prototype;
1202
1203 if (!prototype || !prototype.isReactComponent) {
1204 throw new Error('Can only polyfill class components');
1205 }
1206
1207 if (
1208 typeof Component.getDerivedStateFromProps !== 'function' &&
1209 typeof prototype.getSnapshotBeforeUpdate !== 'function'
1210 ) {
1211 return Component;
1212 }
1213
1214 // If new component APIs are defined, "unsafe" lifecycles won't be called.
1215 // Error if any of these lifecycles are present,
1216 // Because they would work differently between older and newer (16.3+) versions of React.
1217 var foundWillMountName = null;
1218 var foundWillReceivePropsName = null;
1219 var foundWillUpdateName = null;
1220 if (typeof prototype.componentWillMount === 'function') {
1221 foundWillMountName = 'componentWillMount';
1222 } else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
1223 foundWillMountName = 'UNSAFE_componentWillMount';
1224 }
1225 if (typeof prototype.componentWillReceiveProps === 'function') {
1226 foundWillReceivePropsName = 'componentWillReceiveProps';
1227 } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
1228 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
1229 }
1230 if (typeof prototype.componentWillUpdate === 'function') {
1231 foundWillUpdateName = 'componentWillUpdate';
1232 } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
1233 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
1234 }
1235 if (
1236 foundWillMountName !== null ||
1237 foundWillReceivePropsName !== null ||
1238 foundWillUpdateName !== null
1239 ) {
1240 var componentName = Component.displayName || Component.name;
1241 var newApiName =
1242 typeof Component.getDerivedStateFromProps === 'function'
1243 ? 'getDerivedStateFromProps()'
1244 : 'getSnapshotBeforeUpdate()';
1245
1246 throw Error(
1247 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
1248 componentName +
1249 ' uses ' +
1250 newApiName +
1251 ' but also contains the following legacy lifecycles:' +
1252 (foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
1253 (foundWillReceivePropsName !== null
1254 ? '\n ' + foundWillReceivePropsName
1255 : '') +
1256 (foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
1257 '\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
1258 'https://fb.me/react-async-component-lifecycle-hooks'
1259 );
1260 }
1261
1262 // React <= 16.2 does not support static getDerivedStateFromProps.
1263 // As a workaround, use cWM and cWRP to invoke the new static lifecycle.
1264 // Newer versions of React will ignore these lifecycles if gDSFP exists.
1265 if (typeof Component.getDerivedStateFromProps === 'function') {
1266 prototype.componentWillMount = componentWillMount;
1267 prototype.componentWillReceiveProps = componentWillReceiveProps;
1268 }
1269
1270 // React <= 16.2 does not support getSnapshotBeforeUpdate.
1271 // As a workaround, use cWU to invoke the new lifecycle.
1272 // Newer versions of React will ignore that lifecycle if gSBU exists.
1273 if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
1274 if (typeof prototype.componentDidUpdate !== 'function') {
1275 throw new Error(
1276 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
1277 );
1278 }
1279
1280 prototype.componentWillUpdate = componentWillUpdate;
1281
1282 var componentDidUpdate = prototype.componentDidUpdate;
1283
1284 prototype.componentDidUpdate = function componentDidUpdatePolyfill(
1285 prevProps,
1286 prevState,
1287 maybeSnapshot
1288 ) {
1289 // 16.3+ will not execute our will-update method;
1290 // It will pass a snapshot value to did-update though.
1291 // Older versions will require our polyfilled will-update value.
1292 // We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
1293 // Because for <= 15.x versions this might be a "prevContext" object.
1294 // We also can't just check "__reactInternalSnapshot",
1295 // Because get-snapshot might return a falsy value.
1296 // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
1297 var snapshot = this.__reactInternalSnapshotFlag
1298 ? this.__reactInternalSnapshot
1299 : maybeSnapshot;
1300
1301 componentDidUpdate.call(this, prevProps, prevState, snapshot);
1302 };
1303 }
1304
1305 return Component;
1306 }
1307
1308 var specialReactKeys = {
1309 children: true,
1310 key: true,
1311 ref: true
1312 };
1313
1314 var Provider =
1315 /*#__PURE__*/
1316 function (_Component) {
1317 _inherits(Provider, _Component);
1318
1319 function Provider(props, context) {
1320 var _this;
1321
1322 _classCallCheck(this, Provider);
1323
1324 _this = _possibleConstructorReturn(this, _getPrototypeOf(Provider).call(this, props, context));
1325 _this.state = {};
1326 copyStores(props, _this.state);
1327 return _this;
1328 }
1329
1330 _createClass(Provider, [{
1331 key: "render",
1332 value: function render() {
1333 return React.Children.only(this.props.children);
1334 }
1335 }, {
1336 key: "getChildContext",
1337 value: function getChildContext() {
1338 var stores = {}; // inherit stores
1339
1340 copyStores(this.context.mobxStores, stores); // add own stores
1341
1342 copyStores(this.props, stores);
1343 return {
1344 mobxStores: stores
1345 };
1346 }
1347 }], [{
1348 key: "getDerivedStateFromProps",
1349 value: function getDerivedStateFromProps(nextProps, prevState) {
1350 if (!nextProps) return null;
1351 if (!prevState) return nextProps; // Maybe this warning is too aggressive?
1352
1353 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");
1354 if (!nextProps.suppressChangedStoreWarning) for (var key in nextProps) {
1355 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");
1356 }
1357 return nextProps;
1358 }
1359 }]);
1360
1361 return Provider;
1362 }(React.Component);
1363
1364 Provider.contextTypes = {
1365 mobxStores: objectOrObservableObject
1366 };
1367 Provider.childContextTypes = {
1368 mobxStores: objectOrObservableObject.isRequired
1369 };
1370
1371 function copyStores(from, to) {
1372 if (!from) return;
1373
1374 for (var key in from) {
1375 if (validStoreName(key)) to[key] = from[key];
1376 }
1377 }
1378
1379 function validStoreName(key) {
1380 return !specialReactKeys[key] && key !== "suppressChangedStoreWarning";
1381 } // TODO: kill in next major
1382
1383
1384 polyfill(Provider);
1385
1386 var storeKey = newSymbol("disposeOnUnmount");
1387
1388 function runDisposersOnWillUnmount() {
1389 var _this = this;
1390
1391 if (!this[storeKey]) {
1392 // when disposeOnUnmount is only set to some instances of a component it will still patch the prototype
1393 return;
1394 }
1395
1396 this[storeKey].forEach(function (propKeyOrFunction) {
1397 var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction;
1398
1399 if (prop !== undefined && prop !== null) {
1400 if (typeof prop !== "function") {
1401 throw new Error("[mobx-react] disposeOnUnmount only works on functions such as disposers returned by reactions, autorun, etc.");
1402 }
1403
1404 prop();
1405 }
1406 });
1407 this[storeKey] = [];
1408 }
1409
1410 function disposeOnUnmount(target, propertyKeyOrFunction) {
1411 if (Array.isArray(propertyKeyOrFunction)) {
1412 return propertyKeyOrFunction.map(function (fn) {
1413 return disposeOnUnmount(target, fn);
1414 });
1415 }
1416
1417 if (!target instanceof React.Component) {
1418 throw new Error("[mobx-react] disposeOnUnmount only works on class based React components.");
1419 }
1420
1421 if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function") {
1422 throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.");
1423 } // add property key / function we want run (disposed) to the store
1424
1425
1426 var componentWasAlreadyModified = !!target[storeKey];
1427 var store = target[storeKey] || (target[storeKey] = []);
1428 store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already
1429
1430 if (!componentWasAlreadyModified) {
1431 patch(target, "componentWillUnmount", runDisposersOnWillUnmount);
1432 } // return the disposer as is if invoked as a non decorator
1433
1434
1435 if (typeof propertyKeyOrFunction !== "string") {
1436 return propertyKeyOrFunction;
1437 }
1438 }
1439
1440 if (!React.Component) throw new Error("mobx-react requires React to be available");
1441 if (!mobx.spy) throw new Error("mobx-react requires mobx to be available");
1442 if (typeof reactDom.unstable_batchedUpdates === "function") mobx.configure({
1443 reactionScheduler: reactDom.unstable_batchedUpdates
1444 });
1445 var onError = function onError(fn) {
1446 return errorsReporter.on(fn);
1447 };
1448
1449 if ((typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "undefined" ? "undefined" : _typeof(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) === "object") {
1450 var mobx$1 = {
1451 spy: mobx.spy,
1452 extras: {
1453 getDebugName: mobx.getDebugName
1454 }
1455 };
1456 var mobxReact = {
1457 renderReporter: renderReporter,
1458 componentByNodeRegistry: componentByNodeRegistry,
1459 componentByNodeRegistery: componentByNodeRegistry,
1460 trackComponents: trackComponents
1461 };
1462
1463 __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(mobxReact, mobx$1);
1464 }
1465
1466 exports.propTypes = propTypes;
1467 exports.PropTypes = propTypes;
1468 exports.onError = onError;
1469 exports.observer = observer;
1470 exports.Observer = Observer;
1471 exports.renderReporter = renderReporter;
1472 exports.componentByNodeRegistery = componentByNodeRegistry;
1473 exports.componentByNodeRegistry = componentByNodeRegistry;
1474 exports.trackComponents = trackComponents;
1475 exports.useStaticRendering = useStaticRendering;
1476 exports.Provider = Provider;
1477 exports.inject = inject;
1478 exports.disposeOnUnmount = disposeOnUnmount;
1479
1480 Object.defineProperty(exports, '__esModule', { value: true });
1481
1482})));