UNPKG

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