UNPKG

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