UNPKG

2.92 kBJavaScriptView Raw
1/**
2 * Copyright 2015, Yahoo! Inc.
3 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4 */
5const ReactIs = require('react-is');
6const REACT_STATICS = {
7 childContextTypes: true,
8 contextType: true,
9 contextTypes: true,
10 defaultProps: true,
11 displayName: true,
12 getDefaultProps: true,
13 getDerivedStateFromError: true,
14 getDerivedStateFromProps: true,
15 mixins: true,
16 propTypes: true,
17 type: true
18};
19
20const KNOWN_STATICS = {
21 name: true,
22 length: true,
23 prototype: true,
24 caller: true,
25 callee: true,
26 arguments: true,
27 arity: true
28};
29
30const FORWARD_REF_STATICS = {
31 '$$typeof': true,
32 render: true,
33 defaultProps: true,
34 displayName: true,
35 propTypes: true
36};
37
38const MEMO_STATICS = {
39 '$$typeof': true,
40 compare: true,
41 defaultProps: true,
42 displayName: true,
43 propTypes: true,
44 type: true,
45}
46
47const TYPE_STATICS = {};
48TYPE_STATICS[ReactIs.ForwardRef] = FORWARD_REF_STATICS;
49
50function getStatics(component) {
51 if (ReactIs.isMemo(component)) {
52 return MEMO_STATICS;
53 }
54 return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
55}
56
57const defineProperty = Object.defineProperty;
58const getOwnPropertyNames = Object.getOwnPropertyNames;
59const getOwnPropertySymbols = Object.getOwnPropertySymbols;
60const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
61const getPrototypeOf = Object.getPrototypeOf;
62const objectPrototype = Object.prototype;
63
64export default function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
65 if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
66
67 if (objectPrototype) {
68 const inheritedComponent = getPrototypeOf(sourceComponent);
69 if (inheritedComponent && inheritedComponent !== objectPrototype) {
70 hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
71 }
72 }
73
74 let keys = getOwnPropertyNames(sourceComponent);
75
76 if (getOwnPropertySymbols) {
77 keys = keys.concat(getOwnPropertySymbols(sourceComponent));
78 }
79
80 const targetStatics = getStatics(targetComponent);
81 const sourceStatics = getStatics(sourceComponent);
82
83 for (let i = 0; i < keys.length; ++i) {
84 const key = keys[i];
85 if (!KNOWN_STATICS[key] &&
86 !(blacklist && blacklist[key]) &&
87 !(sourceStatics && sourceStatics[key]) &&
88 !(targetStatics && targetStatics[key])
89 ) {
90 const descriptor = getOwnPropertyDescriptor(sourceComponent, key);
91 try { // Avoid failures from read-only properties
92 defineProperty(targetComponent, key, descriptor);
93 } catch (e) {}
94 }
95 }
96
97 return targetComponent;
98 }
99
100 return targetComponent;
101};