UNPKG

2.47 kBJavaScriptView Raw
1var __assign = (this && this.__assign) || function () {
2 __assign = Object.assign || function(t) {
3 for (var s, i = 1, n = arguments.length; i < n; i++) {
4 s = arguments[i];
5 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6 t[p] = s[p];
7 }
8 return t;
9 };
10 return __assign.apply(this, arguments);
11};
12import { forwardRef, memo } from "react";
13import { isUsingStaticRendering } from "./staticRendering";
14import { useObserver } from "./useObserver";
15// n.b. base case is not used for actual typings or exported in the typing files
16export function observer(baseComponent, options) {
17 // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307
18 if (isUsingStaticRendering()) {
19 return baseComponent;
20 }
21 var realOptions = __assign({ forwardRef: false }, options);
22 var baseComponentName = baseComponent.displayName || baseComponent.name;
23 var wrappedComponent = function (props, ref) {
24 return useObserver(function () { return baseComponent(props, ref); }, baseComponentName);
25 };
26 wrappedComponent.displayName = baseComponentName;
27 // memo; we are not interested in deep updates
28 // in props; we assume that if deep objects are changed,
29 // this is in observables, which would have been tracked anyway
30 var memoComponent;
31 if (realOptions.forwardRef) {
32 // we have to use forwardRef here because:
33 // 1. it cannot go before memo, only after it
34 // 2. forwardRef converts the function into an actual component, so we can't let the baseComponent do it
35 // since it wouldn't be a callable function anymore
36 memoComponent = memo(forwardRef(wrappedComponent));
37 }
38 else {
39 memoComponent = memo(wrappedComponent);
40 }
41 copyStaticProperties(baseComponent, memoComponent);
42 memoComponent.displayName = baseComponentName;
43 return memoComponent;
44}
45// based on https://github.com/mridgway/hoist-non-react-statics/blob/master/src/index.js
46var hoistBlackList = {
47 $$typeof: true,
48 render: true,
49 compare: true,
50 type: true
51};
52function copyStaticProperties(base, target) {
53 Object.keys(base).forEach(function (key) {
54 if (!hoistBlackList[key]) {
55 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(base, key));
56 }
57 });
58}
59//# sourceMappingURL=observer.js.map
\No newline at end of file