This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 145
/
Generator.js
305 lines (271 loc) · 8.74 KB
/
Generator.js
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// @flow
/**
* Genertaor is a Component that renders the components, layouts
* with the a given componentTree which is created by qa-compiler
*
* First Step, prerender the tree in constructor, this action will add a
* React Component with all hocs it needs in every node
*
* Second Step, take the node.component to render it, and give the component
* some props it maybe needs such as renderChildren
*/
import * as React from 'react';
import Loadable from 'react-loadable';
import {Item} from 'canner-helpers';
import get from 'lodash/get';
import isUndefined from 'lodash/isUndefined';
import mapValues from 'lodash/mapValues';
import RefId from 'canner-ref-id';
import Layouts from 'canner-layouts';
function defaultHoc(Component) {
return Component;
}
function isComponent(node) {
return node.nodeType && node.nodeType.startsWith('plugins');
}
function isLayout(node) {
return node.nodeType === 'layout';
}
function isFieldset(node) {
return node.packageName === '@canner/antd-object-fieldset';
}
function Loading(props) {
if (props.error) {
return <div>Error! <button onClick={ props.retry }>Retry</button></div>;
} else {
return <div>Loading...</div>;
}
}
export type Node = {
keyName: string,
nodeType: string,
hocs: Array<string>,
children: Array<Node>,
component: React.ComponentType<*>,
loader: Promise<*>
}
type Props = {
componentTree: {[string]: Node},
hocs: {[string]: React.ComponentType<*>},
layouts: {[string]: React.ComponentType<*>},
storages: Object,
goTo: (path: string, search?: Object | string) => void,
baseUrl: string,
routes: Array<string>,
params: {[string]: string},
refresh?: boolean,
deploy?: Function,
reset?: Function,
onDeploy?: Function,
removeOnDeploy?: Function,
hideButtons: boolean,
schema: Object
}
type childrenProps = {
refId: RefId,
[string]: any
};
type State = {
componentTree: {[string]: any},
error: any,
errorInfo: string
}
export default class Generator extends React.PureComponent<Props, State> {
cacheTree: {
[key: string]: Node
} // store the prerenders tree
idNodeMap = {}
constructor(props: Props) {
// prerender the tree in constructor, this action will add a
// React Component with all hocs it needs in every node
super(props);
const {componentTree, routes, goTo} = props;
let activeKey = routes[0];
if (!activeKey) {
activeKey = Object.keys(componentTree)[0];
goTo(activeKey);
}
this.cacheTree = this.genCacheTree(componentTree);
this.state = {
componentTree: this.cacheTree[activeKey],
error: null,
errorInfo: ''
};
}
UNSAFE_componentWillReceiveProps(nextProps: Props) {
if (nextProps.refresh) {
this.cacheTree = this.genCacheTree(nextProps.componentTree);
}
this.setState({
componentTree: this.cacheTree[nextProps.routes[0] || Object.keys(nextProps.componentTree)[0]],
});
}
componentDidCatch(error: any, errorInfo: string) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
genCacheTree = (tree: {[string]: Node}): {[string]: Node} => {
return mapValues(tree, (branch) => {
return this.prerender(branch);
});
}
static defaultProps = {
componentTree: {},
layouts: {},
hocs: {}
}
// wrap the plugin with hoc if it has
prerender = (node: Node): Node => {
// add a field `component` in every node.
// it's a React Component with all hocs it needs in every node
const copyNode = {...node};
let component;
if (isLayout(copyNode)) {
if (typeof copyNode.component === 'string') {
copyNode.component = Layouts[copyNode.component]
}
component = this.wrapByHOC(copyNode.component, (copyNode.hocs || ['containerRouter']).slice() || []);
} else if (isComponent(copyNode)) { // TODO: need to fix, turn plugins to components in compiler
if (isFieldset(copyNode)) {
component = () => <Item />;
} else {
component = Loadable({
loader: () => copyNode.loader || Promise.reject(`There is no loader in ${copyNode.path}`),
loading: Loading,
});
}
component = this.wrapByHOC(component, ['title', 'onDeploy', 'validation', 'deploy', 'request', 'relation', 'query', 'cache', 'route', 'id', 'context', 'errorCatch'] || []);
}
if (!component) {
throw new Error(`invalid node, name: ${copyNode.keyName}, nodeType: ${copyNode.nodeType}`);
}
copyNode.component = component;
if (copyNode.children) {
copyNode.children = copyNode.children.map((child) => {
return this.prerender(child);
});
}
return copyNode;
}
wrapByHOC = (component: React.ComponentType<*>, hocNames: Array<string>): React.ComponentType<*> => {
// find hocs and wrap the component
const {hocs} = this.props;
while (hocNames.length) {
const hocName = hocNames.shift();
const hoc = get(hocs, hocName, defaultHoc);
component = hoc(component);
}
return component;
}
renderNode = (node: Node, index: number, props: childrenProps): React$Node => {
// take the node.component to render it, and give the component
// some props it maybe needs such as renderChildren
// eslint-disable-next-line no-unused-vars
if (!node) {
throw new Error(`Unexpected Error: Want to render a undefined node with refId '${props.refId.toString()}'`);
}
const {component, ...restNodeData} = node;
const {params, goTo, routes, storages, onDeploy, removeOnDeploy, hideButtons, schema} = this.props;
if (node.hidden || props.hidden) {
return null;
}
if (component) {
return <node.component
{...restNodeData}
routes={routes}
key={index}
imageServiceConfig={(storages || {})[routes[0]]}
renderChildren={(props) => this.renderChildren(node, props)}
renderComponent={this.renderComponent}
params={params}
onDeploy={onDeploy}
removeOnDeploy={removeOnDeploy}
hideButtons={hideButtons}
schema={schema}
goTo={(path, search) => {
if (!search) {
const [route, search] = path.split('?');
goTo(route, search);
} else {
goTo(path, search);
}
}}
{...props}
/>;
}
return null;
}
static findNode = (pathArr: Array<string>, node: Node): ?Node => {
if (isComponent(node) && node.keyName === pathArr[0]) {
pathArr = pathArr.slice(1);
if (!pathArr.length) {
return node;
}
}
if (node.children) {
return node.children
.map(child => Generator.findNode(pathArr, child))
.find(node => !!node);
}
}
renderComponent = (refId: RefId, props: childrenProps): React$Node => {
const componentPathArr = refId.getPathArr()
.filter(path => isNaN(Number(path)));
const componentPath = componentPathArr.join('/');
let node = this.idNodeMap[componentPath];
const entryKey = componentPathArr[0];
if (!node) {
const lastPath = componentPathArr.slice(1);
if (lastPath.length === 0) {
node = this.cacheTree[entryKey];
} else {
node = Generator.findNode(componentPathArr.slice(), this.cacheTree[entryKey]);
}
this.idNodeMap[componentPath] = node;
}
if (!node) {
throw new Error(`Can't find the node at refId ${refId.toString()}`);
}
return this.renderNode(node, 0, {...props});
}
renderChildren = (node: Node, props: childrenProps | Node => childrenProps): React$Node => {
// just get the props and call renderNode
// this method is called by components themselves
const {children} = node;
if (children) {
return children.map((child, index) => {
const childProps = typeof props === 'function' ? props(child) : props;
const {refId} = childProps;
if (isUndefined(refId)) {
throw new Error(`refId is required for renderChildren, please check node '${node.keyName || ''}'`);
}
if (childProps.hidden) {
return null;
}
if (childProps.mergeNode) {
// mutate node
childProps.mergeNode(node);
}
return this.renderNode(child, index, childProps);
});
}
return null;
}
render() {
const {componentTree, error, errorInfo} = this.state;
const {routes, params} = this.props;
if (error) {
return errorInfo;
}
return (
<div>
{/* {this.renderComponent(new RefId(routes.join('/')), {refId: new RefId(routes.slice(1).join('/')), routes, params})} */}
{this.renderNode(componentTree, 0, {refId: new RefId(''), routes, params})}
</div>
);
}
}