UNPKG

27.8 kBJavaScriptView Raw
1import { Reaction, _allowStateChanges, _allowStateReadsStart, _allowStateReadsEnd, $mobx, createAtom, untracked, isObservableMap, isObservableObject, isObservableArray, observable } from 'mobx';
2import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react';
3import { isUsingStaticRendering, Observer, observer as observer$1 } from 'mobx-react-lite';
4export { Observer, enableStaticRendering, isUsingStaticRendering, observerBatching, useAsObservableSource, useLocalObservable, useLocalStore, useObserver, useStaticRendering } from 'mobx-react-lite';
5
6var symbolId = 0;
7
8function createSymbol(name) {
9 if (typeof Symbol === "function") {
10 return Symbol(name);
11 }
12
13 var symbol = "__$mobx-react " + name + " (" + symbolId + ")";
14 symbolId++;
15 return symbol;
16}
17
18var createdSymbols = {};
19function newSymbol(name) {
20 if (!createdSymbols[name]) {
21 createdSymbols[name] = createSymbol(name);
22 }
23
24 return createdSymbols[name];
25}
26function shallowEqual(objA, objB) {
27 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
28 if (is(objA, objB)) return true;
29
30 if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
31 return false;
32 }
33
34 var keysA = Object.keys(objA);
35 var keysB = Object.keys(objB);
36 if (keysA.length !== keysB.length) return false;
37
38 for (var i = 0; i < keysA.length; i++) {
39 if (!Object.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
40 return false;
41 }
42 }
43
44 return true;
45}
46
47function is(x, y) {
48 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
49 if (x === y) {
50 return x !== 0 || 1 / x === 1 / y;
51 } else {
52 return x !== x && y !== y;
53 }
54} // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js
55
56
57var hoistBlackList = {
58 $$typeof: 1,
59 render: 1,
60 compare: 1,
61 type: 1,
62 childContextTypes: 1,
63 contextType: 1,
64 contextTypes: 1,
65 defaultProps: 1,
66 getDefaultProps: 1,
67 getDerivedStateFromError: 1,
68 getDerivedStateFromProps: 1,
69 mixins: 1,
70 propTypes: 1
71};
72function copyStaticProperties(base, target) {
73 var protoProps = Object.getOwnPropertyNames(Object.getPrototypeOf(base));
74 Object.getOwnPropertyNames(base).forEach(function (key) {
75 if (!hoistBlackList[key] && protoProps.indexOf(key) === -1) {
76 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key));
77 }
78 });
79}
80/**
81 * Helper to set `prop` to `this` as non-enumerable (hidden prop)
82 * @param target
83 * @param prop
84 * @param value
85 */
86
87function setHiddenProp(target, prop, value) {
88 if (!Object.hasOwnProperty.call(target, prop)) {
89 Object.defineProperty(target, prop, {
90 enumerable: false,
91 configurable: true,
92 writable: true,
93 value: value
94 });
95 } else {
96 target[prop] = value;
97 }
98}
99/**
100 * Utilities for patching componentWillUnmount, to make sure @disposeOnUnmount works correctly icm with user defined hooks
101 * and the handler provided by mobx-react
102 */
103
104var mobxMixins = /*#__PURE__*/newSymbol("patchMixins");
105var mobxPatchedDefinition = /*#__PURE__*/newSymbol("patchedDefinition");
106
107function getMixins(target, methodName) {
108 var mixins = target[mobxMixins] = target[mobxMixins] || {};
109 var methodMixins = mixins[methodName] = mixins[methodName] || {};
110 methodMixins.locks = methodMixins.locks || 0;
111 methodMixins.methods = methodMixins.methods || [];
112 return methodMixins;
113}
114
115function wrapper(realMethod, mixins) {
116 var _this = this;
117
118 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
119 args[_key - 2] = arguments[_key];
120 }
121
122 // locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls
123 mixins.locks++;
124
125 try {
126 var retVal;
127
128 if (realMethod !== undefined && realMethod !== null) {
129 retVal = realMethod.apply(this, args);
130 }
131
132 return retVal;
133 } finally {
134 mixins.locks--;
135
136 if (mixins.locks === 0) {
137 mixins.methods.forEach(function (mx) {
138 mx.apply(_this, args);
139 });
140 }
141 }
142}
143
144function wrapFunction(realMethod, mixins) {
145 var fn = function fn() {
146 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
147 args[_key2] = arguments[_key2];
148 }
149
150 wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args));
151 };
152
153 return fn;
154}
155
156function patch(target, methodName, mixinMethod) {
157 var mixins = getMixins(target, methodName);
158
159 if (mixins.methods.indexOf(mixinMethod) < 0) {
160 mixins.methods.push(mixinMethod);
161 }
162
163 var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName);
164
165 if (oldDefinition && oldDefinition[mobxPatchedDefinition]) {
166 // already patched definition, do not repatch
167 return;
168 }
169
170 var originalMethod = target[methodName];
171 var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod);
172 Object.defineProperty(target, methodName, newDefinition);
173}
174
175function createDefinition(target, methodName, enumerable, mixins, originalMethod) {
176 var _ref;
177
178 var wrappedFunc = wrapFunction(originalMethod, mixins);
179 return _ref = {}, _ref[mobxPatchedDefinition] = true, _ref.get = function get() {
180 return wrappedFunc;
181 }, _ref.set = function set(value) {
182 if (this === target) {
183 wrappedFunc = wrapFunction(value, mixins);
184 } else {
185 // when it is an instance of the prototype/a child prototype patch that particular case again separately
186 // since we need to store separate values depending on wether it is the actual instance, the prototype, etc
187 // e.g. the method for super might not be the same as the method for the prototype which might be not the same
188 // as the method for the instance
189 var newDefinition = createDefinition(this, methodName, enumerable, mixins, value);
190 Object.defineProperty(this, methodName, newDefinition);
191 }
192 }, _ref.configurable = true, _ref.enumerable = enumerable, _ref;
193}
194
195var mobxAdminProperty = $mobx || "$mobx";
196var mobxObserverProperty = /*#__PURE__*/newSymbol("isMobXReactObserver");
197var mobxIsUnmounted = /*#__PURE__*/newSymbol("isUnmounted");
198var skipRenderKey = /*#__PURE__*/newSymbol("skipRender");
199var isForcingUpdateKey = /*#__PURE__*/newSymbol("isForcingUpdate");
200function makeClassComponentObserver(componentClass) {
201 var target = componentClass.prototype;
202
203 if (componentClass[mobxObserverProperty]) {
204 var displayName = getDisplayName(target);
205 console.warn("The provided component class (" + displayName + ") \n has already been declared as an observer component.");
206 } else {
207 componentClass[mobxObserverProperty] = true;
208 }
209
210 if (target.componentWillReact) throw new Error("The componentWillReact life-cycle event is no longer supported");
211
212 if (componentClass["__proto__"] !== PureComponent) {
213 if (!target.shouldComponentUpdate) target.shouldComponentUpdate = observerSCU;else if (target.shouldComponentUpdate !== observerSCU) // n.b. unequal check, instead of existence check, as @observer might be on superclass as well
214 throw new Error("It is not allowed to use shouldComponentUpdate in observer based components.");
215 } // this.props and this.state are made observable, just to make sure @computed fields that
216 // are defined inside the component, and which rely on state or props, re-compute if state or props change
217 // (otherwise the computed wouldn't update and become stale on props change, since props are not observable)
218 // However, this solution is not without it's own problems: https://github.com/mobxjs/mobx-react/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3Aobservable-props-or-not+
219
220
221 makeObservableProp(target, "props");
222 makeObservableProp(target, "state");
223 var baseRender = target.render;
224
225 target.render = function () {
226 return makeComponentReactive.call(this, baseRender);
227 };
228
229 patch(target, "componentWillUnmount", function () {
230 var _this$render$mobxAdmi;
231
232 if (isUsingStaticRendering() === true) return;
233 (_this$render$mobxAdmi = this.render[mobxAdminProperty]) == null ? void 0 : _this$render$mobxAdmi.dispose();
234 this[mobxIsUnmounted] = true;
235
236 if (!this.render[mobxAdminProperty]) {
237 // Render may have been hot-swapped and/or overriden by a subclass.
238 var _displayName = getDisplayName(this);
239
240 console.warn("The reactive render of an observer class component (" + _displayName + ") \n was overriden after MobX attached. This may result in a memory leak if the \n overriden reactive render was not properly disposed.");
241 }
242 });
243 return componentClass;
244} // Generates a friendly name for debugging
245
246function getDisplayName(comp) {
247 return comp.displayName || comp.name || comp.constructor && (comp.constructor.displayName || comp.constructor.name) || "<component>";
248}
249
250function makeComponentReactive(render) {
251 var _this = this;
252
253 if (isUsingStaticRendering() === true) return render.call(this);
254 /**
255 * If props are shallowly modified, react will render anyway,
256 * so atom.reportChanged() should not result in yet another re-render
257 */
258
259 setHiddenProp(this, skipRenderKey, false);
260 /**
261 * forceUpdate will re-assign this.props. We don't want that to cause a loop,
262 * so detect these changes
263 */
264
265 setHiddenProp(this, isForcingUpdateKey, false);
266 var initialName = getDisplayName(this);
267 var baseRender = render.bind(this);
268 var isRenderingPending = false;
269 var reaction = new Reaction(initialName + ".render()", function () {
270 if (!isRenderingPending) {
271 // N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
272 // This unidiomatic React usage but React will correctly warn about this so we continue as usual
273 // See #85 / Pull #44
274 isRenderingPending = true;
275
276 if (_this[mobxIsUnmounted] !== true) {
277 var hasError = true;
278
279 try {
280 setHiddenProp(_this, isForcingUpdateKey, true);
281 if (!_this[skipRenderKey]) Component.prototype.forceUpdate.call(_this);
282 hasError = false;
283 } finally {
284 setHiddenProp(_this, isForcingUpdateKey, false);
285 if (hasError) reaction.dispose();
286 }
287 }
288 }
289 });
290 reaction["reactComponent"] = this;
291 reactiveRender[mobxAdminProperty] = reaction;
292 this.render = reactiveRender;
293
294 function reactiveRender() {
295 isRenderingPending = false;
296 var exception = undefined;
297 var rendering = undefined;
298 reaction.track(function () {
299 try {
300 rendering = _allowStateChanges(false, baseRender);
301 } catch (e) {
302 exception = e;
303 }
304 });
305
306 if (exception) {
307 throw exception;
308 }
309
310 return rendering;
311 }
312
313 return reactiveRender.call(this);
314}
315
316function observerSCU(nextProps, nextState) {
317 if (isUsingStaticRendering()) {
318 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.");
319 } // update on any state changes (as is the default)
320
321
322 if (this.state !== nextState) {
323 return true;
324 } // update if props are shallowly not equal, inspired by PureRenderMixin
325 // we could return just 'false' here, and avoid the `skipRender` checks etc
326 // however, it is nicer if lifecycle events are triggered like usually,
327 // so we return true here if props are shallowly modified.
328
329
330 return !shallowEqual(this.props, nextProps);
331}
332
333function makeObservableProp(target, propName) {
334 var valueHolderKey = newSymbol("reactProp_" + propName + "_valueHolder");
335 var atomHolderKey = newSymbol("reactProp_" + propName + "_atomHolder");
336
337 function getAtom() {
338 if (!this[atomHolderKey]) {
339 setHiddenProp(this, atomHolderKey, createAtom("reactive " + propName));
340 }
341
342 return this[atomHolderKey];
343 }
344
345 Object.defineProperty(target, propName, {
346 configurable: true,
347 enumerable: true,
348 get: function get() {
349 var prevReadState = false;
350
351 if (_allowStateReadsStart && _allowStateReadsEnd) {
352 prevReadState = _allowStateReadsStart(true);
353 }
354
355 getAtom.call(this).reportObserved();
356
357 if (_allowStateReadsStart && _allowStateReadsEnd) {
358 _allowStateReadsEnd(prevReadState);
359 }
360
361 return this[valueHolderKey];
362 },
363 set: function set(v) {
364 if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
365 setHiddenProp(this, valueHolderKey, v);
366 setHiddenProp(this, skipRenderKey, true);
367 getAtom.call(this).reportChanged();
368 setHiddenProp(this, skipRenderKey, false);
369 } else {
370 setHiddenProp(this, valueHolderKey, v);
371 }
372 }
373 });
374}
375
376var hasSymbol = typeof Symbol === "function" && Symbol["for"]; // Using react-is had some issues (and operates on elements, not on types), see #608 / #609
377
378var ReactForwardRefSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.forward_ref") : typeof forwardRef === "function" && /*#__PURE__*/forwardRef(function (props) {
379 return null;
380})["$$typeof"];
381var ReactMemoSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.memo") : typeof memo === "function" && /*#__PURE__*/memo(function (props) {
382 return null;
383})["$$typeof"];
384/**
385 * Observer function / decorator
386 */
387
388function observer(component) {
389 if (component["isMobxInjector"] === true) {
390 console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'");
391 }
392
393 if (ReactMemoSymbol && component["$$typeof"] === ReactMemoSymbol) {
394 throw new Error("Mobx observer: You are trying to use 'observer' on a function component wrapped in either another observer or 'React.memo'. The observer already applies 'React.memo' for you.");
395 } // Unwrap forward refs into `<Observer>` component
396 // we need to unwrap the render, because it is the inner render that needs to be tracked,
397 // not the ForwardRef HoC
398
399
400 if (ReactForwardRefSymbol && component["$$typeof"] === ReactForwardRefSymbol) {
401 var baseRender = component["render"];
402 if (typeof baseRender !== "function") throw new Error("render property of ForwardRef was not a function");
403 return forwardRef(function ObserverForwardRef() {
404 var args = arguments;
405 return createElement(Observer, null, function () {
406 return baseRender.apply(undefined, args);
407 });
408 });
409 } // Function component
410
411
412 if (typeof component === "function" && (!component.prototype || !component.prototype.render) && !component["isReactClass"] && !Object.prototype.isPrototypeOf.call(Component, component)) {
413 return observer$1(component);
414 }
415
416 return makeClassComponentObserver(component);
417}
418
419function _extends() {
420 _extends = Object.assign || function (target) {
421 for (var i = 1; i < arguments.length; i++) {
422 var source = arguments[i];
423
424 for (var key in source) {
425 if (Object.prototype.hasOwnProperty.call(source, key)) {
426 target[key] = source[key];
427 }
428 }
429 }
430
431 return target;
432 };
433
434 return _extends.apply(this, arguments);
435}
436
437function _objectWithoutPropertiesLoose(source, excluded) {
438 if (source == null) return {};
439 var target = {};
440 var sourceKeys = Object.keys(source);
441 var key, i;
442
443 for (i = 0; i < sourceKeys.length; i++) {
444 key = sourceKeys[i];
445 if (excluded.indexOf(key) >= 0) continue;
446 target[key] = source[key];
447 }
448
449 return target;
450}
451
452var MobXProviderContext = /*#__PURE__*/React__default.createContext({});
453function Provider(props) {
454 var children = props.children,
455 stores = _objectWithoutPropertiesLoose(props, ["children"]);
456
457 var parentValue = React__default.useContext(MobXProviderContext);
458 var mutableProviderRef = React__default.useRef(_extends({}, parentValue, stores));
459 var value = mutableProviderRef.current;
460
461 {
462 var newValue = _extends({}, value, stores); // spread in previous state for the context based stores
463
464
465 if (!shallowEqual(value, newValue)) {
466 throw new Error("MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error.");
467 }
468 }
469
470 return React__default.createElement(MobXProviderContext.Provider, {
471 value: value
472 }, children);
473}
474Provider.displayName = "MobXProvider";
475
476/**
477 * Store Injection
478 */
479
480function createStoreInjector(grabStoresFn, component, injectNames, makeReactive) {
481 // Support forward refs
482 var Injector = React__default.forwardRef(function (props, ref) {
483 var newProps = _extends({}, props);
484
485 var context = React__default.useContext(MobXProviderContext);
486 Object.assign(newProps, grabStoresFn(context || {}, newProps) || {});
487
488 if (ref) {
489 newProps.ref = ref;
490 }
491
492 return React__default.createElement(component, newProps);
493 });
494 if (makeReactive) Injector = observer(Injector);
495 Injector["isMobxInjector"] = true; // assigned late to suppress observer warning
496 // Static fields from component should be visible on the generated Injector
497
498 copyStaticProperties(component, Injector);
499 Injector["wrappedComponent"] = component;
500 Injector.displayName = getInjectName(component, injectNames);
501 return Injector;
502}
503
504function getInjectName(component, injectNames) {
505 var displayName;
506 var componentName = component.displayName || component.name || component.constructor && component.constructor.name || "Component";
507 if (injectNames) displayName = "inject-with-" + injectNames + "(" + componentName + ")";else displayName = "inject(" + componentName + ")";
508 return displayName;
509}
510
511function grabStoresByName(storeNames) {
512 return function (baseStores, nextProps) {
513 storeNames.forEach(function (storeName) {
514 if (storeName in nextProps // prefer props over stores
515 ) return;
516 if (!(storeName in baseStores)) throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider");
517 nextProps[storeName] = baseStores[storeName];
518 });
519 return nextProps;
520 };
521}
522/**
523 * higher order component that injects stores to a child.
524 * takes either a varargs list of strings, which are stores read from the context,
525 * or a function that manually maps the available stores from the context to props:
526 * storesToProps(mobxStores, props, context) => newProps
527 */
528
529
530function inject() {
531 for (var _len = arguments.length, storeNames = new Array(_len), _key = 0; _key < _len; _key++) {
532 storeNames[_key] = arguments[_key];
533 }
534
535 if (typeof arguments[0] === "function") {
536 var grabStoresFn = arguments[0];
537 return function (componentClass) {
538 return createStoreInjector(grabStoresFn, componentClass, grabStoresFn.name, true);
539 };
540 } else {
541 return function (componentClass) {
542 return createStoreInjector(grabStoresByName(storeNames), componentClass, storeNames.join("-"), false);
543 };
544 }
545}
546
547var protoStoreKey = /*#__PURE__*/newSymbol("disposeOnUnmountProto");
548var instStoreKey = /*#__PURE__*/newSymbol("disposeOnUnmountInst");
549
550function runDisposersOnWillUnmount() {
551 var _this = this;
552 [].concat(this[protoStoreKey] || [], this[instStoreKey] || []).forEach(function (propKeyOrFunction) {
553 var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction;
554
555 if (prop !== undefined && prop !== null) {
556 if (Array.isArray(prop)) prop.map(function (f) {
557 return f();
558 });else prop();
559 }
560 });
561}
562
563function disposeOnUnmount(target, propertyKeyOrFunction) {
564 if (Array.isArray(propertyKeyOrFunction)) {
565 return propertyKeyOrFunction.map(function (fn) {
566 return disposeOnUnmount(target, fn);
567 });
568 }
569
570 var c = Object.getPrototypeOf(target).constructor;
571 var c2 = Object.getPrototypeOf(target.constructor); // Special case for react-hot-loader
572
573 var c3 = Object.getPrototypeOf(Object.getPrototypeOf(target));
574
575 if (!(c === React__default.Component || c === React__default.PureComponent || c2 === React__default.Component || c2 === React__default.PureComponent || c3 === React__default.Component || c3 === React__default.PureComponent)) {
576 throw new Error("[mobx-react] disposeOnUnmount only supports direct subclasses of React.Component or React.PureComponent.");
577 }
578
579 if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function" && !Array.isArray(propertyKeyOrFunction)) {
580 throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.");
581 } // decorator's target is the prototype, so it doesn't have any instance properties like props
582
583
584 var isDecorator = typeof propertyKeyOrFunction === "string"; // add property key / function we want run (disposed) to the store
585
586 var componentWasAlreadyModified = !!target[protoStoreKey] || !!target[instStoreKey];
587 var store = isDecorator ? // decorators are added to the prototype store
588 target[protoStoreKey] || (target[protoStoreKey] = []) : // functions are added to the instance store
589 target[instStoreKey] || (target[instStoreKey] = []);
590 store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already
591
592 if (!componentWasAlreadyModified) {
593 patch(target, "componentWillUnmount", runDisposersOnWillUnmount);
594 } // return the disposer as is if invoked as a non decorator
595
596
597 if (typeof propertyKeyOrFunction !== "string") {
598 return propertyKeyOrFunction;
599 }
600}
601
602function createChainableTypeChecker(validator) {
603 function checkType(isRequired, props, propName, componentName, location, propFullName) {
604 for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
605 rest[_key - 6] = arguments[_key];
606 }
607
608 return untracked(function () {
609 componentName = componentName || "<<anonymous>>";
610 propFullName = propFullName || propName;
611
612 if (props[propName] == null) {
613 if (isRequired) {
614 var actual = props[propName] === null ? "null" : "undefined";
615 return new Error("The " + location + " `" + propFullName + "` is marked as required " + "in `" + componentName + "`, but its value is `" + actual + "`.");
616 }
617
618 return null;
619 } else {
620 // @ts-ignore rest arg is necessary for some React internals - fails tests otherwise
621 return validator.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest));
622 }
623 });
624 }
625
626 var chainedCheckType = checkType.bind(null, false); // Add isRequired to satisfy Requirable
627
628 chainedCheckType.isRequired = checkType.bind(null, true);
629 return chainedCheckType;
630} // Copied from React.PropTypes
631
632
633function isSymbol(propType, propValue) {
634 // Native Symbol.
635 if (propType === "symbol") {
636 return true;
637 } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
638
639
640 if (propValue["@@toStringTag"] === "Symbol") {
641 return true;
642 } // Fallback for non-spec compliant Symbols which are polyfilled.
643
644
645 if (typeof Symbol === "function" && propValue instanceof Symbol) {
646 return true;
647 }
648
649 return false;
650} // Copied from React.PropTypes
651
652
653function getPropType(propValue) {
654 var propType = typeof propValue;
655
656 if (Array.isArray(propValue)) {
657 return "array";
658 }
659
660 if (propValue instanceof RegExp) {
661 // Old webkits (at least until Android 4.0) return 'function' rather than
662 // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
663 // passes PropTypes.object.
664 return "object";
665 }
666
667 if (isSymbol(propType, propValue)) {
668 return "symbol";
669 }
670
671 return propType;
672} // This handles more types than `getPropType`. Only used for error messages.
673// Copied from React.PropTypes
674
675
676function getPreciseType(propValue) {
677 var propType = getPropType(propValue);
678
679 if (propType === "object") {
680 if (propValue instanceof Date) {
681 return "date";
682 } else if (propValue instanceof RegExp) {
683 return "regexp";
684 }
685 }
686
687 return propType;
688}
689
690function createObservableTypeCheckerCreator(allowNativeType, mobxType) {
691 return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
692 return untracked(function () {
693 if (allowNativeType) {
694 if (getPropType(props[propName]) === mobxType.toLowerCase()) return null;
695 }
696
697 var mobxChecker;
698
699 switch (mobxType) {
700 case "Array":
701 mobxChecker = isObservableArray;
702 break;
703
704 case "Object":
705 mobxChecker = isObservableObject;
706 break;
707
708 case "Map":
709 mobxChecker = isObservableMap;
710 break;
711
712 default:
713 throw new Error("Unexpected mobxType: " + mobxType);
714 }
715
716 var propValue = props[propName];
717
718 if (!mobxChecker(propValue)) {
719 var preciseType = getPreciseType(propValue);
720 var nativeTypeExpectationMessage = allowNativeType ? " or javascript `" + mobxType.toLowerCase() + "`" : "";
721 return new Error("Invalid prop `" + propFullName + "` of type `" + preciseType + "` supplied to" + " `" + componentName + "`, expected `mobx.Observable" + mobxType + "`" + nativeTypeExpectationMessage + ".");
722 }
723
724 return null;
725 });
726 });
727}
728
729function createObservableArrayOfTypeChecker(allowNativeType, typeChecker) {
730 return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
731 for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {
732 rest[_key2 - 5] = arguments[_key2];
733 }
734
735 return untracked(function () {
736 if (typeof typeChecker !== "function") {
737 return new Error("Property `" + propFullName + "` of component `" + componentName + "` has " + "invalid PropType notation.");
738 } else {
739 var error = createObservableTypeCheckerCreator(allowNativeType, "Array")(props, propName, componentName, location, propFullName);
740 if (error instanceof Error) return error;
741 var propValue = props[propName];
742
743 for (var i = 0; i < propValue.length; i++) {
744 error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + "[" + i + "]"].concat(rest));
745 if (error instanceof Error) return error;
746 }
747
748 return null;
749 }
750 });
751 });
752}
753
754var observableArray = /*#__PURE__*/createObservableTypeCheckerCreator(false, "Array");
755var observableArrayOf = /*#__PURE__*/createObservableArrayOfTypeChecker.bind(null, false);
756var observableMap = /*#__PURE__*/createObservableTypeCheckerCreator(false, "Map");
757var observableObject = /*#__PURE__*/createObservableTypeCheckerCreator(false, "Object");
758var arrayOrObservableArray = /*#__PURE__*/createObservableTypeCheckerCreator(true, "Array");
759var arrayOrObservableArrayOf = /*#__PURE__*/createObservableArrayOfTypeChecker.bind(null, true);
760var objectOrObservableObject = /*#__PURE__*/createObservableTypeCheckerCreator(true, "Object");
761var PropTypes = {
762 observableArray: observableArray,
763 observableArrayOf: observableArrayOf,
764 observableMap: observableMap,
765 observableObject: observableObject,
766 arrayOrObservableArray: arrayOrObservableArray,
767 arrayOrObservableArrayOf: arrayOrObservableArrayOf,
768 objectOrObservableObject: objectOrObservableObject
769};
770
771if (!Component) throw new Error("mobx-react requires React to be available");
772if (!observable) throw new Error("mobx-react requires mobx to be available");
773
774export { MobXProviderContext, PropTypes, Provider, disposeOnUnmount, inject, observer };
775//# sourceMappingURL=mobx-react.esm.development.js.map