mobxreact.rn.module.js 27 KB

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