forked from alibaba/lowcode-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
121 lines (109 loc) · 2.7 KB
/
Copy pathindex.ts
File metadata and controls
121 lines (109 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { isEmpty } from 'lodash';
// import * as path from 'path';
// @ts-ignore
import parsePropTypes from 'parse-prop-types';
import PropTypes from 'prop-types';
import { transformItem } from '../transform';
import requireInSandbox from './requireInSandbox';
export interface IComponentInfo {
component: any;
meta: {
exportName: string;
subName?: string;
};
}
const reservedKeys = [
'propTypes',
'defaultProps',
'name',
'arguments',
'caller',
'length',
'contextTypes',
'displayName',
'__esModule',
'version',
];
function getKeys(com: any) {
const keys = Object.keys(com).filter(x => {
return !reservedKeys.includes(x) && !x.startsWith('_');
});
return keys;
}
function isComponent(obj: any) {
return (
typeof obj === 'function' &&
(Object.prototype.hasOwnProperty.call(obj, 'propTypes') ||
Object.prototype.hasOwnProperty.call(obj, 'defaultProps'))
);
}
export default function (filePath: string) {
// const { filePath } = arg;
// const modulePath = path.resolve(workDir, 'node_modules', 'parse-prop-types');
// const parsePropTypes = require(modulePath).default;
if (!filePath) return [];
const Com = requireInSandbox(filePath, PropTypes);
const components: IComponentInfo[] = [];
let index = 0;
if (Com.__esModule) {
const keys = getKeys(Com);
keys.forEach(k => {
if (isComponent(Com[k])) {
components.push({
component: Com[k],
meta: {
exportName: k,
},
});
}
});
} else if (isComponent(Com)) {
components.push({
component: Com,
meta: {
exportName: 'default',
},
});
}
// dps
while (index < components.length) {
const item = components[index++];
const keys = getKeys(item.component);
const subs = keys
.filter(k => isComponent(item.component[k]))
.map(k => ({
component: item.component[k],
meta: {
...item.meta,
subName: k,
},
}));
if (subs.length) {
components.splice(index, 0, ...subs);
}
}
const result = components.reduce((acc: any, { meta, component }) => {
const componentInfo = parsePropTypes(component);
if (!isEmpty(componentInfo)) {
const props = Object.keys(componentInfo).reduce((acc2: any[], name) => {
try {
const item: any = transformItem(name, componentInfo[name]);
acc2.push(item);
} catch (e) {
// TODO
}
return acc2;
}, []);
return [
...acc,
{
meta,
props,
componentName: meta.subName || meta.exportName || component.displayName,
},
];
}
return acc;
}, []);
return result;
}