mobx-react-lite
Advanced tools
Comparing version 3.2.3 to 3.3.0
# mobx-react-lite | ||
## 3.3.0 | ||
### Minor Changes | ||
- [`59b42c28`](https://github.com/mobxjs/mobx/commit/59b42c2826208435353ce6bf154ae59077edcc05) [#3282](https://github.com/mobxjs/mobx/pull/3282) Thanks [@urugator](https://github.com/urugator)! - support `observable(forwardRef(fn))`, deprecate `observable(fn, { forwardRef: true })`, solve #2527, #3267 | ||
## 3.2.3 | ||
@@ -4,0 +10,0 @@ |
@@ -119,20 +119,2 @@ 'use strict'; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -421,4 +403,26 @@ if (!o) return; | ||
function observer(baseComponent, options) { | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol["for"]; // Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.forward_ref") : typeof React.forwardRef === "function" && /*#__PURE__*/React.forwardRef(function (props) { | ||
return null; | ||
})["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.memo") : typeof React.memo === "function" && /*#__PURE__*/React.memo(function (props) { | ||
return null; | ||
})["$$typeof"]; // n.b. base case is not used for actual typings or exported in the typing files | ||
function observer(baseComponent, // TODO remove in next major | ||
options) { | ||
var _options$forwardRef; | ||
if ( warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
if (isUsingStaticRendering()) { | ||
@@ -428,11 +432,19 @@ return baseComponent; | ||
var realOptions = _extends({ | ||
forwardRef: false | ||
}, options); | ||
var useForwardRef = (_options$forwardRef = options == null ? void 0 : options.forwardRef) != null ? _options$forwardRef : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; // If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
var wrappedComponent = function wrappedComponent(props, ref) { | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function observerComponent(props, ref) { | ||
return useObserver(function () { | ||
return baseComponent(props, ref); | ||
return render(props, ref); | ||
}, baseComponentName); | ||
@@ -444,3 +456,3 @@ }; // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
observerComponent.displayName = baseComponentName; | ||
} // Support legacy context: `contextTypes` must be applied before `memo` | ||
@@ -450,3 +462,10 @@ | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = React.forwardRef(observerComponent); | ||
} // memo; we are not interested in deep updates | ||
@@ -457,18 +476,7 @@ // in props; we assume that if deep objects are changed, | ||
var memoComponent; | ||
observerComponent = React.memo(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = React.memo(React.forwardRef(wrappedComponent)); | ||
} else { | ||
memoComponent = React.memo(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
{ | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function set() { | ||
@@ -482,3 +490,3 @@ var _this$type; | ||
return memoComponent; | ||
return observerComponent; | ||
} // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js | ||
@@ -485,0 +493,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,r=require("mobx"),t=require("react"),n=(e=t)&&"object"==typeof e&&"default"in e?e.default:e,o=require("react-dom");if(!t.useState)throw new Error("mobx-react-lite requires React with Hooks support");if(!r.makeObservable)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function i(e){e()}function u(e){e||(e=i),r.configure({reactionScheduler:e})}function a(e){return r.getDependencyTree(e)}var c="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function s(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+f}}var f=1e4;function l(e){var r=new Map,t=1,n=new e((function(e){var t=r.get(e);t&&(t.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,i){var u=t++;return n.register(i,u,e),e.current=s(o),e.current.finalizationRegistryCleanupToken=u,r.set(u,e.current),e.current},recordReactionAsCommitted:function(e){n.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function d(){return(d=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function p(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function v(){var e,r=new Set;function t(){void 0===e&&(e=setTimeout(n,1e4))}function n(){e=void 0;var n=Date.now();r.forEach((function(e){var t=e.current;t&&n>=t.cleanAt&&(t.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&t()}return{addReactionToTrack:function(e,n,o){return e.current=s(n),r.add(e),t(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),n())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var t,n=function(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return p(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?p(e,void 0):void 0}}(e))){t&&(e=t);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(t=n()).done;){var o=t.value,i=o.current;i&&(i.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var b=c?l(c):v(),m=b.addReactionToTrack,y=b.recordReactionAsCommitted,g=b.resetCleanupScheduleForTests,h=!1;function T(e){h=e}function w(){return h}function R(e){return"observer"+e}var x=function(){};function S(){return new x}function O(e,t){if(void 0===t&&(t="observed"),w())return e();var o=n.useState(S)[0],i=n.useState()[1],u=function(){return i([])},c=n.useRef(null);if(!c.current)var s=new r.Reaction(R(t),(function(){f.mounted?u():f.changedBeforeMount=!0})),f=m(c,s,o);var l,d,p=c.current.reaction;if(n.useDebugValue(p,a),n.useEffect((function(){return y(c),c.current?(c.current.mounted=!0,c.current.changedBeforeMount&&(c.current.changedBeforeMount=!1,u())):(c.current={reaction:new r.Reaction(R(t),(function(){u()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},u()),function(){c.current.reaction.dispose(),c.current=null}}),[]),p.track((function(){try{l=e()}catch(e){d=e}})),d)throw d;return l}var A={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function C(e){var r=e.children||e.render;return"function"!=typeof r?null:O(r)}function j(e){var n=t.useState((function(){return r.observable(e,{},{deep:!1})}))[0];return r.runInAction((function(){Object.assign(n,e)})),n}C.displayName="Observer",u(o.unstable_batchedUpdates),exports.Observer=C,exports.clearTimers=g,exports.enableStaticRendering=T,exports.isObserverBatched=function(){return!0},exports.isUsingStaticRendering=w,exports.observer=function(e,r){if(w())return e;var n,o,i,u=d({forwardRef:!1},r),a=e.displayName||e.name,c=function(r,t){return O((function(){return e(r,t)}),a)};return""!==a&&(c.displayName=a),e.contextTypes&&(c.contextTypes=e.contextTypes),n=t.memo(u.forwardRef?t.forwardRef(c):c),o=e,i=n,Object.keys(o).forEach((function(e){A[e]||Object.defineProperty(i,e,Object.getOwnPropertyDescriptor(o,e))})),n},exports.observerBatching=u,exports.useAsObservableSource=j,exports.useLocalObservable=function(e,n){return t.useState((function(){return r.observable(e(),n,{autoBind:!0})}))[0]},exports.useLocalStore=function(e,n){var o=n&&j(n);return t.useState((function(){return r.observable(e(o),void 0,{autoBind:!0})}))[0]},exports.useObserver=function(e,r){return void 0===r&&(r="observed"),O(e,r)},exports.useStaticRendering=function(e){T(e)}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,r=require("mobx"),t=require("react"),n=(e=t)&&"object"==typeof e&&"default"in e?e.default:e,o=require("react-dom");if(!t.useState)throw new Error("mobx-react-lite requires React with Hooks support");if(!r.makeObservable)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function u(e){e()}function i(e){e||(e=u),r.configure({reactionScheduler:e})}function a(e){return r.getDependencyTree(e)}var c="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function f(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+s}}var s=1e4;function l(e){var r=new Map,t=1,n=new e((function(e){var t=r.get(e);t&&(t.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,u){var i=t++;return n.register(u,i,e),e.current=f(o),e.current.finalizationRegistryCleanupToken=i,r.set(i,e.current),e.current},recordReactionAsCommitted:function(e){n.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function d(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function p(){var e,r=new Set;function t(){void 0===e&&(e=setTimeout(n,1e4))}function n(){e=void 0;var n=Date.now();r.forEach((function(e){var t=e.current;t&&n>=t.cleanAt&&(t.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&t()}return{addReactionToTrack:function(e,n,o){return e.current=f(n),r.add(e),t(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),n())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var t,n=function(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return d(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?d(e,void 0):void 0}}(e))){t&&(e=t);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(t=n()).done;){var o=t.value,u=o.current;u&&(u.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var v=c?l(c):p(),m=v.addReactionToTrack,b=v.recordReactionAsCommitted,y=v.resetCleanupScheduleForTests,w=!1;function h(e){w=e}function g(){return w}function T(e){return"observer"+e}var R=function(){};function S(){return new R}function x(e,t){if(void 0===t&&(t="observed"),g())return e();var o=n.useState(S)[0],u=n.useState()[1],i=function(){return u([])},c=n.useRef(null);if(!c.current)var f=new r.Reaction(T(t),(function(){s.mounted?i():s.changedBeforeMount=!0})),s=m(c,f,o);var l,d,p=c.current.reaction;if(n.useDebugValue(p,a),n.useEffect((function(){return b(c),c.current?(c.current.mounted=!0,c.current.changedBeforeMount&&(c.current.changedBeforeMount=!1,i())):(c.current={reaction:new r.Reaction(T(t),(function(){i()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},i()),function(){c.current.reaction.dispose(),c.current=null}}),[]),p.track((function(){try{l=e()}catch(e){d=e}})),d)throw d;return l}var O="function"==typeof Symbol&&Symbol.for,A=O?Symbol.for("react.forward_ref"):"function"==typeof t.forwardRef&&t.forwardRef((function(e){return null})).$$typeof,C=O?Symbol.for("react.memo"):"function"==typeof t.memo&&t.memo((function(e){return null})).$$typeof,$={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function k(e){var r=e.children||e.render;return"function"!=typeof r?null:x(r)}function j(e){var n=t.useState((function(){return r.observable(e,{},{deep:!1})}))[0];return r.runInAction((function(){Object.assign(n,e)})),n}k.displayName="Observer",i(o.unstable_batchedUpdates),exports.Observer=k,exports.clearTimers=y,exports.enableStaticRendering=h,exports.isObserverBatched=function(){return!0},exports.isUsingStaticRendering=g,exports.observer=function(e,r){var n;if(C&&e.$$typeof===C)throw new Error("[mobx-react-lite] 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.");if(g())return e;var o=null!=(n=null==r?void 0:r.forwardRef)&&n,u=e,i=e.displayName||e.name;if(A&&e.$$typeof===A&&(o=!0,"function"!=typeof(u=e.render)))throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function");var a,c,f=function(e,r){return x((function(){return u(e,r)}),i)};return""!==i&&(f.displayName=i),e.contextTypes&&(f.contextTypes=e.contextTypes),o&&(f=t.forwardRef(f)),f=t.memo(f),a=e,c=f,Object.keys(a).forEach((function(e){$[e]||Object.defineProperty(c,e,Object.getOwnPropertyDescriptor(a,e))})),f},exports.observerBatching=i,exports.useAsObservableSource=j,exports.useLocalObservable=function(e,n){return t.useState((function(){return r.observable(e(),n,{autoBind:!0})}))[0]},exports.useLocalStore=function(e,n){var o=n&&j(n);return t.useState((function(){return r.observable(e(o),void 0,{autoBind:!0})}))[0]},exports.useObserver=function(e,r){return void 0===r&&(r="observed"),x(e,r)},exports.useStaticRendering=function(e){h(e)}; | ||
//# sourceMappingURL=mobxreactlite.cjs.production.min.js.map |
import { makeObservable, configure, getDependencyTree, Reaction, observable, runInAction } from 'mobx'; | ||
import React, { useState, memo, forwardRef } from 'react'; | ||
import React, { useState, forwardRef, memo } from 'react'; | ||
import { unstable_batchedUpdates } from 'react-dom'; | ||
@@ -112,20 +112,2 @@ | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -414,4 +396,26 @@ if (!o) return; | ||
function observer(baseComponent, options) { | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol["for"]; // Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.forward_ref") : typeof forwardRef === "function" && /*#__PURE__*/forwardRef(function (props) { | ||
return null; | ||
})["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.memo") : typeof memo === "function" && /*#__PURE__*/memo(function (props) { | ||
return null; | ||
})["$$typeof"]; // n.b. base case is not used for actual typings or exported in the typing files | ||
function observer(baseComponent, // TODO remove in next major | ||
options) { | ||
var _options$forwardRef; | ||
if ( warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
if (isUsingStaticRendering()) { | ||
@@ -421,11 +425,19 @@ return baseComponent; | ||
var realOptions = _extends({ | ||
forwardRef: false | ||
}, options); | ||
var useForwardRef = (_options$forwardRef = options == null ? void 0 : options.forwardRef) != null ? _options$forwardRef : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; // If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
var wrappedComponent = function wrappedComponent(props, ref) { | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function observerComponent(props, ref) { | ||
return useObserver(function () { | ||
return baseComponent(props, ref); | ||
return render(props, ref); | ||
}, baseComponentName); | ||
@@ -437,3 +449,3 @@ }; // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
observerComponent.displayName = baseComponentName; | ||
} // Support legacy context: `contextTypes` must be applied before `memo` | ||
@@ -443,3 +455,10 @@ | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = forwardRef(observerComponent); | ||
} // memo; we are not interested in deep updates | ||
@@ -450,18 +469,7 @@ // in props; we assume that if deep objects are changed, | ||
var memoComponent; | ||
observerComponent = memo(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = memo(forwardRef(wrappedComponent)); | ||
} else { | ||
memoComponent = memo(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
{ | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function set() { | ||
@@ -475,3 +483,3 @@ var _this$type; | ||
return memoComponent; | ||
return observerComponent; | ||
} // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js | ||
@@ -478,0 +486,0 @@ |
import { makeObservable, configure, getDependencyTree, Reaction, observable, runInAction } from 'mobx'; | ||
import React, { useState, memo, forwardRef } from 'react'; | ||
import React, { useState, forwardRef, memo } from 'react'; | ||
import { unstable_batchedUpdates } from 'react-dom'; | ||
@@ -112,20 +112,2 @@ | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -414,4 +396,26 @@ if (!o) return; | ||
function observer(baseComponent, options) { | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol["for"]; // Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.forward_ref") : typeof forwardRef === "function" && /*#__PURE__*/forwardRef(function (props) { | ||
return null; | ||
})["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.memo") : typeof memo === "function" && /*#__PURE__*/memo(function (props) { | ||
return null; | ||
})["$$typeof"]; // n.b. base case is not used for actual typings or exported in the typing files | ||
function observer(baseComponent, // TODO remove in next major | ||
options) { | ||
var _options$forwardRef; | ||
if (process.env.NODE_ENV !== "production" && warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
if (isUsingStaticRendering()) { | ||
@@ -421,11 +425,19 @@ return baseComponent; | ||
var realOptions = _extends({ | ||
forwardRef: false | ||
}, options); | ||
var useForwardRef = (_options$forwardRef = options == null ? void 0 : options.forwardRef) != null ? _options$forwardRef : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; // If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
var wrappedComponent = function wrappedComponent(props, ref) { | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function observerComponent(props, ref) { | ||
return useObserver(function () { | ||
return baseComponent(props, ref); | ||
return render(props, ref); | ||
}, baseComponentName); | ||
@@ -437,3 +449,3 @@ }; // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
observerComponent.displayName = baseComponentName; | ||
} // Support legacy context: `contextTypes` must be applied before `memo` | ||
@@ -443,3 +455,10 @@ | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = forwardRef(observerComponent); | ||
} // memo; we are not interested in deep updates | ||
@@ -450,18 +469,7 @@ // in props; we assume that if deep objects are changed, | ||
var memoComponent; | ||
observerComponent = memo(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = memo(forwardRef(wrappedComponent)); | ||
} else { | ||
memoComponent = memo(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
if ("production" !== process.env.NODE_ENV) { | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function set() { | ||
@@ -475,3 +483,3 @@ var _this$type; | ||
return memoComponent; | ||
return observerComponent; | ||
} // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js | ||
@@ -478,0 +486,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{makeObservable as e,configure as r,getDependencyTree as n,Reaction as t,observable as o,runInAction as i}from"mobx";import u,{useState as c,memo as a,forwardRef as f}from"react";import{unstable_batchedUpdates as s}from"react-dom";if(!c)throw new Error("mobx-react-lite requires React with Hooks support");if(!e)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function d(e){e()}function l(e){e||(e=d),r({reactionScheduler:e})}var v=function(){return!0};function p(e){return n(e)}var m="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function y(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+b}}var b=1e4;function h(e){var r=new Map,n=1,t=new e((function(e){var n=r.get(e);n&&(n.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,i){var u=n++;return t.register(i,u,e),e.current=y(o),e.current.finalizationRegistryCleanupToken=u,r.set(u,e.current),e.current},recordReactionAsCommitted:function(e){t.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function T(){return(T=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e}).apply(this,arguments)}function g(e,r){(null==r||r>e.length)&&(r=e.length);for(var n=0,t=new Array(r);n<r;n++)t[n]=e[n];return t}function w(){var e,r=new Set;function n(){void 0===e&&(e=setTimeout(t,1e4))}function t(){e=void 0;var t=Date.now();r.forEach((function(e){var n=e.current;n&&t>=n.cleanAt&&(n.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&n()}return{addReactionToTrack:function(e,t,o){return e.current=y(t),r.add(e),n(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),t())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var n,t=function(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return g(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?g(e,void 0):void 0}}(e))){n&&(e=n);var t=0;return function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(n=t()).done;){var o=n.value,i=o.current;i&&(i.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var R=m?h(m):w(),O=R.addReactionToTrack,A=R.recordReactionAsCommitted,C=R.resetCleanupScheduleForTests,S=!1;function j(e){S=e}function k(){return S}function x(e){return"observer"+e}var z=function(){};function B(){return new z}function F(e,r){if(void 0===r&&(r="observed"),k())return e();var n=u.useState(B)[0],o=u.useState()[1],i=function(){return o([])},c=u.useRef(null);if(!c.current)var a=new t(x(r),(function(){f.mounted?i():f.changedBeforeMount=!0})),f=O(c,a,n);var s,d,l=c.current.reaction;if(u.useDebugValue(l,p),u.useEffect((function(){return A(c),c.current?(c.current.mounted=!0,c.current.changedBeforeMount&&(c.current.changedBeforeMount=!1,i())):(c.current={reaction:new t(x(r),(function(){i()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},i()),function(){c.current.reaction.dispose(),c.current=null}}),[]),l.track((function(){try{s=e()}catch(e){d=e}})),d)throw d;return s}function M(e,r){if(k())return e;var n,t,o,i=T({forwardRef:!1},r),u=e.displayName||e.name,c=function(r,n){return F((function(){return e(r,n)}),u)};return""!==u&&(c.displayName=u),e.contextTypes&&(c.contextTypes=e.contextTypes),n=a(i.forwardRef?f(c):c),t=e,o=n,Object.keys(t).forEach((function(e){E[e]||Object.defineProperty(o,e,Object.getOwnPropertyDescriptor(t,e))})),n}var E={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function N(e){var r=e.children||e.render;return"function"!=typeof r?null:F(r)}function D(e,r){return c((function(){return o(e(),r,{autoBind:!0})}))[0]}function I(e){var r=c((function(){return o(e,{},{deep:!1})}))[0];return i((function(){Object.assign(r,e)})),r}function P(e,r){var n=r&&I(r);return c((function(){return o(e(n),void 0,{autoBind:!0})}))[0]}function $(e,r){return void 0===r&&(r="observed"),F(e,r)}function q(e){j(e)}N.displayName="Observer",l(s);export{N as Observer,C as clearTimers,j as enableStaticRendering,v as isObserverBatched,k as isUsingStaticRendering,M as observer,l as observerBatching,I as useAsObservableSource,D as useLocalObservable,P as useLocalStore,$ as useObserver,q as useStaticRendering}; | ||
import{makeObservable as e,configure as r,getDependencyTree as n,Reaction as t,observable as o,runInAction as i}from"mobx";import u,{useState as a,forwardRef as c,memo as f}from"react";import{unstable_batchedUpdates as l}from"react-dom";if(!a)throw new Error("mobx-react-lite requires React with Hooks support");if(!e)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function s(e){e()}function d(e){e||(e=s),r({reactionScheduler:e})}var p=function(){return!0};function m(e){return n(e)}var v="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function y(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+b}}var b=1e4;function w(e){var r=new Map,n=1,t=new e((function(e){var n=r.get(e);n&&(n.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,i){var u=n++;return t.register(i,u,e),e.current=y(o),e.current.finalizationRegistryCleanupToken=u,r.set(u,e.current),e.current},recordReactionAsCommitted:function(e){t.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function h(e,r){(null==r||r>e.length)&&(r=e.length);for(var n=0,t=new Array(r);n<r;n++)t[n]=e[n];return t}function T(){var e,r=new Set;function n(){void 0===e&&(e=setTimeout(t,1e4))}function t(){e=void 0;var t=Date.now();r.forEach((function(e){var n=e.current;n&&t>=n.cleanAt&&(n.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&n()}return{addReactionToTrack:function(e,t,o){return e.current=y(t),r.add(e),n(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),t())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var n,t=function(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return h(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?h(e,void 0):void 0}}(e))){n&&(e=n);var t=0;return function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(n=t()).done;){var o=n.value,i=o.current;i&&(i.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var g=v?w(v):T(),R=g.addReactionToTrack,S=g.recordReactionAsCommitted,A=g.resetCleanupScheduleForTests,C=!1;function x(e){C=e}function $(){return C}function O(e){return"observer"+e}var k=function(){};function E(){return new k}function F(e,r){if(void 0===r&&(r="observed"),$())return e();var n=u.useState(E)[0],o=u.useState()[1],i=function(){return o([])},a=u.useRef(null);if(!a.current)var c=new t(O(r),(function(){f.mounted?i():f.changedBeforeMount=!0})),f=R(a,c,n);var l,s,d=a.current.reaction;if(u.useDebugValue(d,m),u.useEffect((function(){return S(a),a.current?(a.current.mounted=!0,a.current.changedBeforeMount&&(a.current.changedBeforeMount=!1,i())):(a.current={reaction:new t(O(r),(function(){i()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},i()),function(){a.current.reaction.dispose(),a.current=null}}),[]),d.track((function(){try{l=e()}catch(e){s=e}})),s)throw s;return l}var j="function"==typeof Symbol&&Symbol.for,z=j?Symbol.for("react.forward_ref"):"function"==typeof c&&c((function(e){return null})).$$typeof,B=j?Symbol.for("react.memo"):"function"==typeof f&&f((function(e){return null})).$$typeof;function M(e,r){var n;if(B&&e.$$typeof===B)throw new Error("[mobx-react-lite] 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.");if($())return e;var t=null!=(n=null==r?void 0:r.forwardRef)&&n,o=e,i=e.displayName||e.name;if(z&&e.$$typeof===z&&(t=!0,"function"!=typeof(o=e.render)))throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function");var u,a,l=function(e,r){return F((function(){return o(e,r)}),i)};return""!==i&&(l.displayName=i),e.contextTypes&&(l.contextTypes=e.contextTypes),t&&(l=c(l)),l=f(l),u=e,a=l,Object.keys(u).forEach((function(e){N[e]||Object.defineProperty(a,e,Object.getOwnPropertyDescriptor(u,e))})),l}var N={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function D(e){var r=e.children||e.render;return"function"!=typeof r?null:F(r)}function I(e,r){return a((function(){return o(e(),r,{autoBind:!0})}))[0]}function q(e){var r=a((function(){return o(e,{},{deep:!1})}))[0];return i((function(){Object.assign(r,e)})),r}function P(e,r){var n=r&&q(r);return a((function(){return o(e(n),void 0,{autoBind:!0})}))[0]}function H(e,r){return void 0===r&&(r="observed"),F(e,r)}function U(e){x(e)}D.displayName="Observer",d(l);export{D as Observer,A as clearTimers,x as enableStaticRendering,p as isObserverBatched,$ as isUsingStaticRendering,M as observer,d as observerBatching,q as useAsObservableSource,I as useLocalObservable,P as useLocalStore,H as useObserver,U as useStaticRendering}; | ||
//# sourceMappingURL=mobxreactlite.esm.production.min.js.map |
@@ -116,20 +116,2 @@ (function (global, factory) { | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -418,4 +400,26 @@ if (!o) return; | ||
function observer(baseComponent, options) { | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol["for"]; // Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.forward_ref") : typeof React.forwardRef === "function" && /*#__PURE__*/React.forwardRef(function (props) { | ||
return null; | ||
})["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol ? /*#__PURE__*/Symbol["for"]("react.memo") : typeof React.memo === "function" && /*#__PURE__*/React.memo(function (props) { | ||
return null; | ||
})["$$typeof"]; // n.b. base case is not used for actual typings or exported in the typing files | ||
function observer(baseComponent, // TODO remove in next major | ||
options) { | ||
var _options$forwardRef; | ||
if ( warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
if (isUsingStaticRendering()) { | ||
@@ -425,11 +429,19 @@ return baseComponent; | ||
var realOptions = _extends({ | ||
forwardRef: false | ||
}, options); | ||
var useForwardRef = (_options$forwardRef = options == null ? void 0 : options.forwardRef) != null ? _options$forwardRef : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; // If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
var wrappedComponent = function wrappedComponent(props, ref) { | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function observerComponent(props, ref) { | ||
return useObserver(function () { | ||
return baseComponent(props, ref); | ||
return render(props, ref); | ||
}, baseComponentName); | ||
@@ -441,3 +453,3 @@ }; // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
observerComponent.displayName = baseComponentName; | ||
} // Support legacy context: `contextTypes` must be applied before `memo` | ||
@@ -447,3 +459,10 @@ | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = React.forwardRef(observerComponent); | ||
} // memo; we are not interested in deep updates | ||
@@ -454,18 +473,7 @@ // in props; we assume that if deep objects are changed, | ||
var memoComponent; | ||
observerComponent = React.memo(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = React.memo(React.forwardRef(wrappedComponent)); | ||
} else { | ||
memoComponent = React.memo(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
{ | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function set() { | ||
@@ -479,3 +487,3 @@ var _this$type; | ||
return memoComponent; | ||
return observerComponent; | ||
} // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js | ||
@@ -482,0 +490,0 @@ |
@@ -1,2 +0,2 @@ | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("mobx"),require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","mobx","react","react-dom"],r):r((e=e||self).mobxReactLite={},e.mobx,e.React,e.ReactDOM)}(this,(function(e,r,t,n){"use strict";var o="default"in t?t.default:t;if(!t.useState)throw new Error("mobx-react-lite requires React with Hooks support");if(!r.makeObservable)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function i(e){e()}function u(e){e||(e=i),r.configure({reactionScheduler:e})}function a(e){return r.getDependencyTree(e)}var c="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function f(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+s}}var s=1e4;function d(e){var r=new Map,t=1,n=new e((function(e){var t=r.get(e);t&&(t.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,i){var u=t++;return n.register(i,u,e),e.current=f(o),e.current.finalizationRegistryCleanupToken=u,r.set(u,e.current),e.current},recordReactionAsCommitted:function(e){n.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function l(){return(l=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function v(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function p(){var e,r=new Set;function t(){void 0===e&&(e=setTimeout(n,1e4))}function n(){e=void 0;var n=Date.now();r.forEach((function(e){var t=e.current;t&&n>=t.cleanAt&&(t.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&t()}return{addReactionToTrack:function(e,n,o){return e.current=f(n),r.add(e),t(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),n())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var t,n=function(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return v(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?v(e,void 0):void 0}}(e))){t&&(e=t);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(t=n()).done;){var o=t.value,i=o.current;i&&(i.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var b=c?d(c):p(),m=b.addReactionToTrack,y=b.recordReactionAsCommitted,g=b.resetCleanupScheduleForTests,h=!1;function T(e){h=e}function R(){return h}function w(e){return"observer"+e}var S=function(){};function O(){return new S}function x(e,t){if(void 0===t&&(t="observed"),R())return e();var n=o.useState(O)[0],i=o.useState()[1],u=function(){return i([])},c=o.useRef(null);if(!c.current)var f=new r.Reaction(w(t),(function(){s.mounted?u():s.changedBeforeMount=!0})),s=m(c,f,n);var d,l,v=c.current.reaction;if(o.useDebugValue(v,a),o.useEffect((function(){return y(c),c.current?(c.current.mounted=!0,c.current.changedBeforeMount&&(c.current.changedBeforeMount=!1,u())):(c.current={reaction:new r.Reaction(w(t),(function(){u()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},u()),function(){c.current.reaction.dispose(),c.current=null}}),[]),v.track((function(){try{d=e()}catch(e){l=e}})),l)throw l;return d}var A={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function C(e){var r=e.children||e.render;return"function"!=typeof r?null:x(r)}function j(e){var n=t.useState((function(){return r.observable(e,{},{deep:!1})}))[0];return r.runInAction((function(){Object.assign(n,e)})),n}C.displayName="Observer",u(n.unstable_batchedUpdates),e.Observer=C,e.clearTimers=g,e.enableStaticRendering=T,e.isObserverBatched=function(){return!0},e.isUsingStaticRendering=R,e.observer=function(e,r){if(R())return e;var n,o,i,u=l({forwardRef:!1},r),a=e.displayName||e.name,c=function(r,t){return x((function(){return e(r,t)}),a)};return""!==a&&(c.displayName=a),e.contextTypes&&(c.contextTypes=e.contextTypes),n=t.memo(u.forwardRef?t.forwardRef(c):c),o=e,i=n,Object.keys(o).forEach((function(e){A[e]||Object.defineProperty(i,e,Object.getOwnPropertyDescriptor(o,e))})),n},e.observerBatching=u,e.useAsObservableSource=j,e.useLocalObservable=function(e,n){return t.useState((function(){return r.observable(e(),n,{autoBind:!0})}))[0]},e.useLocalStore=function(e,n){var o=n&&j(n);return t.useState((function(){return r.observable(e(o),void 0,{autoBind:!0})}))[0]},e.useObserver=function(e,r){return void 0===r&&(r="observed"),x(e,r)},e.useStaticRendering=function(e){T(e)},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("mobx"),require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","mobx","react","react-dom"],r):r((e=e||self).mobxReactLite={},e.mobx,e.React,e.ReactDOM)}(this,(function(e,r,t,n){"use strict";var o="default"in t?t.default:t;if(!t.useState)throw new Error("mobx-react-lite requires React with Hooks support");if(!r.makeObservable)throw new Error("mobx-react-lite@3 requires mobx at least version 6 to be available");function i(e){e()}function u(e){e||(e=i),r.configure({reactionScheduler:e})}function a(e){return r.getDependencyTree(e)}var c="undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry;function f(e){return{reaction:e,mounted:!1,changedBeforeMount:!1,cleanAt:Date.now()+s}}var s=1e4;function d(e){var r=new Map,t=1,n=new e((function(e){var t=r.get(e);t&&(t.reaction.dispose(),r.delete(e))}));return{addReactionToTrack:function(e,o,i){var u=t++;return n.register(i,u,e),e.current=f(o),e.current.finalizationRegistryCleanupToken=u,r.set(u,e.current),e.current},recordReactionAsCommitted:function(e){n.unregister(e),e.current&&e.current.finalizationRegistryCleanupToken&&r.delete(e.current.finalizationRegistryCleanupToken)},forceCleanupTimerToRunNowForTests:function(){},resetCleanupScheduleForTests:function(){}}}function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function m(){var e,r=new Set;function t(){void 0===e&&(e=setTimeout(n,1e4))}function n(){e=void 0;var n=Date.now();r.forEach((function(e){var t=e.current;t&&n>=t.cleanAt&&(t.reaction.dispose(),e.current=null,r.delete(e))})),r.size>0&&t()}return{addReactionToTrack:function(e,n,o){return e.current=f(n),r.add(e),t(),e.current},recordReactionAsCommitted:function(e){r.delete(e)},forceCleanupTimerToRunNowForTests:function(){e&&(clearTimeout(e),n())},resetCleanupScheduleForTests:function(){if(r.size>0){for(var t,n=function(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return l(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,void 0):void 0}}(e))){t&&(e=t);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(r);!(t=n()).done;){var o=t.value,i=o.current;i&&(i.reaction.dispose(),o.current=null)}r.clear()}e&&(clearTimeout(e),e=void 0)}}}var p=c?d(c):m(),v=p.addReactionToTrack,b=p.recordReactionAsCommitted,y=p.resetCleanupScheduleForTests,h=!1;function w(e){h=e}function g(){return h}function R(e){return"observer"+e}var T=function(){};function S(){return new T}function x(e,t){if(void 0===t&&(t="observed"),g())return e();var n=o.useState(S)[0],i=o.useState()[1],u=function(){return i([])},c=o.useRef(null);if(!c.current)var f=new r.Reaction(R(t),(function(){s.mounted?u():s.changedBeforeMount=!0})),s=v(c,f,n);var d,l,m=c.current.reaction;if(o.useDebugValue(m,a),o.useEffect((function(){return b(c),c.current?(c.current.mounted=!0,c.current.changedBeforeMount&&(c.current.changedBeforeMount=!1,u())):(c.current={reaction:new r.Reaction(R(t),(function(){u()})),mounted:!0,changedBeforeMount:!1,cleanAt:Infinity},u()),function(){c.current.reaction.dispose(),c.current=null}}),[]),m.track((function(){try{d=e()}catch(e){l=e}})),l)throw l;return d}var O="function"==typeof Symbol&&Symbol.for,A=O?Symbol.for("react.forward_ref"):"function"==typeof t.forwardRef&&t.forwardRef((function(e){return null})).$$typeof,C=O?Symbol.for("react.memo"):"function"==typeof t.memo&&t.memo((function(e){return null})).$$typeof,$={$$typeof:!0,render:!0,compare:!0,type:!0,displayName:!0};function k(e){var r=e.children||e.render;return"function"!=typeof r?null:x(r)}function j(e){var n=t.useState((function(){return r.observable(e,{},{deep:!1})}))[0];return r.runInAction((function(){Object.assign(n,e)})),n}k.displayName="Observer",u(n.unstable_batchedUpdates),e.Observer=k,e.clearTimers=y,e.enableStaticRendering=w,e.isObserverBatched=function(){return!0},e.isUsingStaticRendering=g,e.observer=function(e,r){var n;if(C&&e.$$typeof===C)throw new Error("[mobx-react-lite] 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.");if(g())return e;var o=null!=(n=null==r?void 0:r.forwardRef)&&n,i=e,u=e.displayName||e.name;if(A&&e.$$typeof===A&&(o=!0,"function"!=typeof(i=e.render)))throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function");var a,c,f=function(e,r){return x((function(){return i(e,r)}),u)};return""!==u&&(f.displayName=u),e.contextTypes&&(f.contextTypes=e.contextTypes),o&&(f=t.forwardRef(f)),f=t.memo(f),a=e,c=f,Object.keys(a).forEach((function(e){$[e]||Object.defineProperty(c,e,Object.getOwnPropertyDescriptor(a,e))})),f},e.observerBatching=u,e.useAsObservableSource=j,e.useLocalObservable=function(e,n){return t.useState((function(){return r.observable(e(),n,{autoBind:!0})}))[0]},e.useLocalStore=function(e,n){var o=n&&j(n);return t.useState((function(){return r.observable(e(o),void 0,{autoBind:!0})}))[0]},e.useObserver=function(e,r){return void 0===r&&(r="observed"),x(e,r)},e.useStaticRendering=function(e){w(e)},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=mobxreactlite.umd.production.min.js.map |
@@ -8,2 +8,3 @@ /// <reference types="react" /> | ||
}): React.MemoExoticComponent<React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>>; | ||
export declare function observer<P extends object, TRef = {}>(baseComponent: React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>): React.MemoExoticComponent<React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>>; | ||
export declare function observer<P extends object>(baseComponent: React.FunctionComponent<P>, options?: IObserverOptions): React.FunctionComponent<P>; | ||
@@ -10,0 +11,0 @@ export declare function observer<C extends React.FunctionComponent<any> | React.RefForwardingComponent<any>, Options extends IObserverOptions>(baseComponent: C, options?: Options): Options extends { |
@@ -1,17 +0,25 @@ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
import { forwardRef, memo } from "react"; | ||
import { isUsingStaticRendering } from "./staticRendering"; | ||
import { useObserver } from "./useObserver"; | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol.for; | ||
// Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol | ||
? Symbol.for("react.forward_ref") | ||
: typeof forwardRef === "function" && forwardRef(function (props) { return null; })["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol | ||
? Symbol.for("react.memo") | ||
: typeof memo === "function" && memo(function (props) { return null; })["$$typeof"]; | ||
// n.b. base case is not used for actual typings or exported in the typing files | ||
export function observer(baseComponent, options) { | ||
export function observer(baseComponent, | ||
// TODO remove in next major | ||
options) { | ||
var _a; | ||
if (process.env.NODE_ENV !== "production" && warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
@@ -21,6 +29,16 @@ if (isUsingStaticRendering()) { | ||
} | ||
var realOptions = __assign({ forwardRef: false }, options); | ||
var useForwardRef = (_a = options === null || options === void 0 ? void 0 : options.forwardRef) !== null && _a !== void 0 ? _a : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
var wrappedComponent = function (props, ref) { | ||
return useObserver(function () { return baseComponent(props, ref); }, baseComponentName); | ||
// If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function (props, ref) { | ||
return useObserver(function () { return render(props, ref); }, baseComponentName); | ||
}; | ||
@@ -30,25 +48,23 @@ // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
; | ||
observerComponent.displayName = baseComponentName; | ||
} | ||
// Support legacy context: `contextTypes` must be applied before `memo` | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = forwardRef(observerComponent); | ||
} | ||
// memo; we are not interested in deep updates | ||
// in props; we assume that if deep objects are changed, | ||
// this is in observables, which would have been tracked anyway | ||
var memoComponent; | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = memo(forwardRef(wrappedComponent)); | ||
} | ||
else { | ||
memoComponent = memo(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
observerComponent = memo(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if ("production" !== process.env.NODE_ENV) { | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function () { | ||
@@ -60,3 +76,3 @@ var _a; | ||
} | ||
return memoComponent; | ||
return observerComponent; | ||
} | ||
@@ -63,0 +79,0 @@ // based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -18,4 +7,23 @@ exports.observer = void 0; | ||
var useObserver_1 = require("./useObserver"); | ||
var warnObserverOptionsDeprecated = true; | ||
var hasSymbol = typeof Symbol === "function" && Symbol.for; | ||
// Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
var ReactForwardRefSymbol = hasSymbol | ||
? Symbol.for("react.forward_ref") | ||
: typeof react_1.forwardRef === "function" && (0, react_1.forwardRef)(function (props) { return null; })["$$typeof"]; | ||
var ReactMemoSymbol = hasSymbol | ||
? Symbol.for("react.memo") | ||
: typeof react_1.memo === "function" && (0, react_1.memo)(function (props) { return null; })["$$typeof"]; | ||
// n.b. base case is not used for actual typings or exported in the typing files | ||
function observer(baseComponent, options) { | ||
function observer(baseComponent, | ||
// TODO remove in next major | ||
options) { | ||
var _a; | ||
if (process.env.NODE_ENV !== "production" && warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false; | ||
console.warn("[mobx-react-lite] `observer(fn, { forwardRef: true })` is depreacted, use `observer(React.forwardRef(fn))`"); | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error("[mobx-react-lite] 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."); | ||
} | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
@@ -25,6 +33,16 @@ if ((0, staticRendering_1.isUsingStaticRendering)()) { | ||
} | ||
var realOptions = __assign({ forwardRef: false }, options); | ||
var useForwardRef = (_a = options === null || options === void 0 ? void 0 : options.forwardRef) !== null && _a !== void 0 ? _a : false; | ||
var render = baseComponent; | ||
var baseComponentName = baseComponent.displayName || baseComponent.name; | ||
var wrappedComponent = function (props, ref) { | ||
return (0, useObserver_1.useObserver)(function () { return baseComponent(props, ref); }, baseComponentName); | ||
// If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true; | ||
render = baseComponent["render"]; | ||
if (typeof render !== "function") { | ||
throw new Error("[mobx-react-lite] `render` property of ForwardRef was not a function"); | ||
} | ||
} | ||
var observerComponent = function (props, ref) { | ||
return (0, useObserver_1.useObserver)(function () { return render(props, ref); }, baseComponentName); | ||
}; | ||
@@ -34,25 +52,23 @@ // Don't set `displayName` for anonymous components, | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName; | ||
; | ||
observerComponent.displayName = baseComponentName; | ||
} | ||
// Support legacy context: `contextTypes` must be applied before `memo` | ||
if (baseComponent.contextTypes) { | ||
wrappedComponent.contextTypes = baseComponent.contextTypes; | ||
; | ||
observerComponent.contextTypes = baseComponent.contextTypes; | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = (0, react_1.forwardRef)(observerComponent); | ||
} | ||
// memo; we are not interested in deep updates | ||
// in props; we assume that if deep objects are changed, | ||
// this is in observables, which would have been tracked anyway | ||
var memoComponent; | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = (0, react_1.memo)((0, react_1.forwardRef)(wrappedComponent)); | ||
} | ||
else { | ||
memoComponent = (0, react_1.memo)(wrappedComponent); | ||
} | ||
copyStaticProperties(baseComponent, memoComponent); | ||
observerComponent = (0, react_1.memo)(observerComponent); | ||
copyStaticProperties(baseComponent, observerComponent); | ||
if ("production" !== process.env.NODE_ENV) { | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set: function () { | ||
@@ -64,3 +80,3 @@ var _a; | ||
} | ||
return memoComponent; | ||
return observerComponent; | ||
} | ||
@@ -67,0 +83,0 @@ exports.observer = observer; |
{ | ||
"name": "mobx-react-lite", | ||
"version": "3.2.3", | ||
"version": "3.3.0", | ||
"description": "Lightweight React bindings for MobX based on React 16.8+ and Hooks", | ||
@@ -53,3 +53,3 @@ "source": "src/index.ts", | ||
"devDependencies": { | ||
"mobx": "^6.3.6", | ||
"mobx": "^6.4.0", | ||
"expose-gc": "^1.0.0" | ||
@@ -56,0 +56,0 @@ }, |
@@ -6,2 +6,14 @@ import { forwardRef, memo } from "react" | ||
let warnObserverOptionsDeprecated = true | ||
const hasSymbol = typeof Symbol === "function" && Symbol.for | ||
// Using react-is had some issues (and operates on elements, not on types), see #608 / #609 | ||
const ReactForwardRefSymbol = hasSymbol | ||
? Symbol.for("react.forward_ref") | ||
: typeof forwardRef === "function" && forwardRef((props: any) => null)["$$typeof"] | ||
const ReactMemoSymbol = hasSymbol | ||
? Symbol.for("react.memo") | ||
: typeof memo === "function" && memo((props: any) => null)["$$typeof"] | ||
export interface IObserverOptions { | ||
@@ -18,2 +30,10 @@ readonly forwardRef?: boolean | ||
export function observer<P extends object, TRef = {}>( | ||
baseComponent: React.ForwardRefExoticComponent< | ||
React.PropsWithoutRef<P> & React.RefAttributes<TRef> | ||
> | ||
): React.MemoExoticComponent< | ||
React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>> | ||
> | ||
export function observer<P extends object>( | ||
@@ -43,5 +63,22 @@ baseComponent: React.FunctionComponent<P>, | ||
export function observer<P extends object, TRef = {}>( | ||
baseComponent: React.RefForwardingComponent<TRef, P> | React.FunctionComponent<P>, | ||
baseComponent: | ||
| React.RefForwardingComponent<TRef, P> | ||
| React.FunctionComponent<P> | ||
| React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>, | ||
// TODO remove in next major | ||
options?: IObserverOptions | ||
) { | ||
if (process.env.NODE_ENV !== "production" && warnObserverOptionsDeprecated && options) { | ||
warnObserverOptionsDeprecated = false | ||
console.warn( | ||
`[mobx-react-lite] \`observer(fn, { forwardRef: true })\` is depreacted, use \`observer(React.forwardRef(fn))\`` | ||
) | ||
} | ||
if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) { | ||
throw new Error( | ||
`[mobx-react-lite] 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.` | ||
) | ||
} | ||
// The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307 | ||
@@ -52,17 +89,27 @@ if (isUsingStaticRendering()) { | ||
const realOptions = { | ||
forwardRef: false, | ||
...options | ||
} | ||
let useForwardRef = options?.forwardRef ?? false | ||
let render = baseComponent | ||
const baseComponentName = baseComponent.displayName || baseComponent.name | ||
const wrappedComponent = (props: P, ref: React.Ref<TRef>) => { | ||
return useObserver(() => baseComponent(props, ref), baseComponentName) | ||
// If already wrapped with forwardRef, unwrap, | ||
// so we can patch render and apply memo | ||
if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) { | ||
useForwardRef = true | ||
render = baseComponent["render"] | ||
if (typeof render !== "function") { | ||
throw new Error( | ||
`[mobx-react-lite] \`render\` property of ForwardRef was not a function` | ||
) | ||
} | ||
} | ||
let observerComponent = (props: P, ref: React.Ref<TRef>) => { | ||
return useObserver(() => render(props, ref), baseComponentName) | ||
} | ||
// Don't set `displayName` for anonymous components, | ||
// so the `displayName` can be customized by user, see #3192. | ||
if (baseComponentName !== "") { | ||
wrappedComponent.displayName = baseComponentName | ||
;(observerComponent as React.FunctionComponent).displayName = baseComponentName | ||
} | ||
@@ -72,23 +119,23 @@ | ||
if ((baseComponent as any).contextTypes) { | ||
wrappedComponent.contextTypes = (baseComponent as any).contextTypes | ||
;(observerComponent as React.FunctionComponent).contextTypes = ( | ||
baseComponent as any | ||
).contextTypes | ||
} | ||
if (useForwardRef) { | ||
// `forwardRef` must be applied prior `memo` | ||
// `forwardRef(observer(cmp))` throws: | ||
// "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))" | ||
observerComponent = forwardRef(observerComponent) | ||
} | ||
// memo; we are not interested in deep updates | ||
// in props; we assume that if deep objects are changed, | ||
// this is in observables, which would have been tracked anyway | ||
let memoComponent | ||
if (realOptions.forwardRef) { | ||
// we have to use forwardRef here because: | ||
// 1. it cannot go before memo, only after it | ||
// 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it | ||
// since it wouldn't be a callable function anymore | ||
memoComponent = memo(forwardRef(wrappedComponent)) | ||
} else { | ||
memoComponent = memo(wrappedComponent) | ||
} | ||
observerComponent = memo(observerComponent) | ||
copyStaticProperties(baseComponent, memoComponent) | ||
copyStaticProperties(baseComponent, observerComponent) | ||
if ("production" !== process.env.NODE_ENV) { | ||
Object.defineProperty(memoComponent, "contextTypes", { | ||
Object.defineProperty(observerComponent, "contextTypes", { | ||
set() { | ||
@@ -104,3 +151,3 @@ throw new Error( | ||
return memoComponent | ||
return observerComponent | ||
} | ||
@@ -107,0 +154,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
513830
4064
28