* Copyright (c) 2023 Huawei Technologies Co.,Ltd.
*
* openInula is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
import { isMemo, ForwardRef } from 'openinula';
import { INULA_FORWARD_REF_STATICS, INULA_MEMO_STATICS, INULA_STATICS, NATIVE_STATICS } from '../constants';
const staticsMap = new Map();
staticsMap.set(ForwardRef, INULA_FORWARD_REF_STATICS);
function getStatics(component) {
if (isMemo(component)) {
return INULA_MEMO_STATICS;
}
if (staticsMap.has(component['vtype'])) {
return staticsMap.get(component['vtype']) || INULA_STATICS;
}
}
* 判断给定的对象属性描述是否有效
* @param sourceComponent
* @param key
*/
function isDescriptorValid<U>(sourceComponent: U, key: string | symbol) {
const descriptor = Object.getOwnPropertyDescriptor(sourceComponent, key);
return descriptor && (!descriptor.get || descriptor.get.prototype);
}
function copyStaticProps<T, U>(targetComponent: T, sourceComponent: U): T {
if (typeof sourceComponent === 'string') {
return targetComponent;
}
const inheritedComponent = Object.getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== Object.prototype) {
copyStaticProps(targetComponent, inheritedComponent);
}
const keys: (string | symbol)[] = [
...Object.getOwnPropertyNames(sourceComponent),
...Object.getOwnPropertySymbols(sourceComponent),
];
const targetStatics = getStatics(targetComponent);
const sourceStatics = getStatics(sourceComponent);
keys.forEach(key => {
if (
!NATIVE_STATICS[key] &&
!(targetStatics && targetStatics[key]) &&
!(sourceStatics && sourceStatics[key]) &&
isDescriptorValid(sourceComponent, key)
) {
try {
Object.defineProperty(targetComponent, key, Object.getOwnPropertyDescriptor(sourceComponent, key)!);
} catch (e) {
console.log('Error occurred while copying static props:', e);
}
}
});
return targetComponent;
}
export default copyStaticProps;