UNPKG

2.58 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 = require('react');
7const REACT_STATICS = {
8 childContextTypes: true,
9 contextType: true,
10 contextTypes: true,
11 defaultProps: true,
12 displayName: true,
13 getDefaultProps: 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};
34
35const TYPE_STATICS = {};
36TYPE_STATICS[ReactIs.ForwardRef] = FORWARD_REF_STATICS;
37
38const defineProperty = Object.defineProperty;
39const getOwnPropertyNames = Object.getOwnPropertyNames;
40const getOwnPropertySymbols = Object.getOwnPropertySymbols;
41const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
42const getPrototypeOf = Object.getPrototypeOf;
43const objectPrototype = Object.prototype;
44
45export default function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
46 if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
47
48 if (objectPrototype) {
49 const inheritedComponent = getPrototypeOf(sourceComponent);
50 if (inheritedComponent && inheritedComponent !== objectPrototype) {
51 hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
52 }
53 }
54
55 let keys = getOwnPropertyNames(sourceComponent);
56
57 if (getOwnPropertySymbols) {
58 keys = keys.concat(getOwnPropertySymbols(sourceComponent));
59 }
60
61 const targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS;
62 const sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS;
63
64 for (let i = 0; i < keys.length; ++i) {
65 const key = keys[i];
66 if (!KNOWN_STATICS[key] &&
67 !(blacklist && blacklist[key]) &&
68 !(sourceStatics && sourceStatics[key]) &&
69 !(targetStatics && targetStatics[key])
70 ) {
71 const descriptor = getOwnPropertyDescriptor(sourceComponent, key);
72 try { // Avoid failures from read-only properties
73 defineProperty(targetComponent, key, descriptor);
74 } catch (e) {}
75 }
76 }
77
78 return targetComponent;
79 }
80
81 return targetComponent;
82};