-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathGISDK.tsx
426 lines (397 loc) · 12.4 KB
/
GISDK.tsx
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import Graphin, { GraphinData } from '@antv/graphin';
import { original } from 'immer';
import React, { useMemo } from 'react';
import { useImmer } from 'use-immer';
import { defaultInitializerCfg } from './Initializer';
import SizeSensor from './SizeSensor';
import FitCenterAfterMount from './components/FitCenterAfterMount';
import { GraphInsightContext } from './context';
import getComponents from './hooks/useComponents';
import './index.less';
import * as utils from './process';
import { registerLayouts, registerShapes } from './register';
import type { Props, State } from './typing';
import { GIComponentConfig } from './typing';
import { createUuid } from './process/common';
// @ts-ignore
let updateHistoryTimer: NodeJS.Timer;
/** export */
const GISDK = (props: Props) => {
const graphinRef = React.useRef<null | Graphin>(null);
// @ts-ignore
const { children, assets, id, services, config } = props;
const GISDK_ID = React.useMemo(() => {
if (!id) {
const defaultId = `${Math.random().toString(36).substr(2)}`;
console.warn(`⚠️: props.id 缺失,默认生成 GISDK_ID : ${defaultId} 用于多实例管理`);
return defaultId;
}
return id;
}, []);
const { components: ComponentAssets, elements: ElementAssets, layouts: LayoutAssets } = assets;
registerShapes(ElementAssets);
registerLayouts(LayoutAssets);
const [state, updateState] = useImmer<State>({
data: { nodes: [], edges: [] } as GraphinData,
propertyGraphData: undefined,
schemaData: {
//会在初始化时候更新
nodes: [],
edges: [],
},
source: { nodes: [], edges: [] } as GraphinData,
layout: {},
components: [] as GIComponentConfig[],
config: props.config,
isLoading: false,
isContextReady: false,
initialized: false,
initializer: defaultInitializerCfg,
transform: (data, reset?: boolean) => data,
layoutCache: false,
largeGraphLimit: 2000,
largeGraphData: undefined,
GICC_LAYOUT: {
id: 'EmptyLayout',
props: {},
},
//@ts-ignore
GISDK_ID,
});
React.useEffect(() => {
updateState(draft => {
draft.config = props.config;
});
}, [props.config]);
const {
layout: layoutCfg,
components: componentsCfg = [],
nodes: nodesCfg,
edges: edgesCfg,
pageLayout,
} = state.config;
/** 根据注册的图元素,生成Transform函数 */
React.useEffect(() => {
let GICC_LAYOUT = { id: 'EmptyLayout', props: {} };
let INITIALIZER;
if (pageLayout) GICC_LAYOUT = pageLayout;
componentsCfg.forEach(item => {
if (pageLayout) {
if (item.id === pageLayout.id) {
GICC_LAYOUT = item;
return;
}
} else if (item.type === 'GICC_LAYOUT') {
GICC_LAYOUT = item;
return;
}
if (item.type === 'INITIALIZER' || item.props.GI_INITIALIZER) {
INITIALIZER = item;
return;
}
});
updateState(draft => {
draft.config.components = componentsCfg;
draft.components = componentsCfg;
if (INITIALIZER.id !== draft.initializer?.id) {
//@ts-ignore
draft.initializer = INITIALIZER;
}
draft.layoutCache = true;
//@ts-ignore
draft.GICC_LAYOUT = GICC_LAYOUT;
});
}, [componentsCfg, pageLayout]);
React.useEffect(() => {
if (!layoutCfg) {
return;
}
stopForceSimulation();
// @ts-ignore
const { type, ...options } = layoutCfg.props || {};
//@ts-ignore
let otherOptions = {};
if (options && options.defSpringLenCfg) {
//@ts-ignore
otherOptions = {
defSpringLen: utils.getDefSpringLenFunction(options.defSpringLenCfg),
};
}
// 资金力导布局定制
if (layoutCfg.id === 'FundForce') {
otherOptions = {
defSideCoe: utils.getDefSideCoeFunction(options.income, options.outcome, options.isLog, options.multiple),
};
}
if (layoutCfg.id === 'Force2') {
const {
advanceWeight,
edgeWeightField,
nodeWeightField,
nodeWeightFieldFromEdge,
nodeWeightFromType,
directed,
directedFromType,
directedInWeightField,
directedOutWeightField,
directedIsLog,
directedMultiple,
directedAmountFromEdge,
} = options;
(otherOptions as any).defSideCoe = 'unset';
if (advanceWeight) {
if (edgeWeightField) {
(otherOptions as any).edgeStrength = utils.getEdgeWeightedStrength(options);
}
if (
(nodeWeightFromType === 'node' && nodeWeightField) ||
(nodeWeightFromType === 'edge' && nodeWeightFieldFromEdge)
) {
(otherOptions as any).nodeStrength = utils.getNodeWeightedStrength(options);
}
if (directed) {
if (directedFromType === 'node') {
(otherOptions as any).defSideCoe = utils.getDefSideCoeFunction(
directedInWeightField,
directedOutWeightField,
directedIsLog,
directedMultiple,
);
} else if (directedAmountFromEdge) {
(otherOptions as any).defSideCoe = utils.getDefSideCoeFromEdgeFunction(
directedAmountFromEdge,
directedIsLog,
directedMultiple,
);
}
}
}
}
updateState(draft => {
draft.layout = {
type,
...options,
...otherOptions,
// 保证更新布局,因为有些函数映射的参数在 Graphin 内部被 JSON.stringify 后无法对比出区别
seed: Math.random(),
};
draft.config.layout = layoutCfg;
draft.layoutCache = false;
});
}, [layoutCfg]);
/** 增加多元素 */
React.useEffect(() => {
if (!nodesCfg || !edgesCfg || nodesCfg.length === 0 || edgesCfg.length === 0) {
return;
}
/**
*
* @param data 源数据
* @param reset 是否重置:按照 Node/Edge Schema来视觉映射
* @returns
*/
const transform = (data, reset?: boolean) => {
const nodes = utils.transDataByConfig('nodes', data, { nodes: nodesCfg, edges: edgesCfg }, ElementAssets, reset);
const edges = utils.transDataByConfig('edges', data, { nodes: nodesCfg, edges: edgesCfg }, ElementAssets, reset);
const { combos, tableResult } = data;
return {
nodes,
edges,
combos,
tableResult,
};
};
updateState(draft => {
if (draft.data.nodes.length !== 0) {
const preData = original(draft.data);
// 当节点和边的Schema配置变化的时候,默认是重置视觉映射;
const newData = transform(preData, true);
//@ts-ignore
draft.data = newData;
}
draft.transform = transform;
draft.config.nodes = nodesCfg;
draft.config.edges = edgesCfg;
});
}, [nodesCfg, edgesCfg]);
// @ts-ignore
const { data, layout, components, initializer, theme, transform, GICC_LAYOUT } = state;
// console.log('%c G6VP Render...', 'color:red', state.layout);
const sourceDataMap = useMemo(() => {
const nodes = state.source.nodes.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {});
const edges = state.source.edges.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {});
return {
nodes,
edges,
};
}, [state.source]);
const stopForceSimulation = () => {
if (graphinRef.current) {
const { layout, graph } = graphinRef.current;
const { instance } = layout;
if (instance) {
const { type, simulation } = instance;
if (type === 'graphin-force') {
simulation.stop();
return;
}
}
const layoutController = graph.get('layoutController');
const layoutMethod = layoutController.layoutMethods?.[0];
if (layoutMethod?.type === 'force2') {
layoutMethod.stop();
}
}
};
const restartForceSimulation = (nodes = []) => {
if (graphinRef.current) {
const { layout: graphLayout, graph } = graphinRef.current;
const { instance } = graphLayout;
if (instance) {
const { type, simulation } = instance;
if (type === 'graphin-force') {
simulation.restart(nodes, graph);
return;
}
}
const layoutController = graph.get('layoutController');
const layoutMethod = layoutController.layoutMethods?.[0];
if (layoutMethod?.type === 'force2') {
graph.updateLayout({ animate: true, disableTriggerLayout: false });
updateState(draft => {
draft.layout.animate = true;
});
}
}
};
const ContextValue = {
...state,
GISDK_ID,
services,
assets,
sourceDataMap,
graph: graphinRef.current?.graph,
theme: graphinRef.current?.theme,
apis: graphinRef.current?.apis,
layoutInstance: graphinRef.current?.layout,
updateContext: updateState,
updateData: res => {
updateState(draft => {
const newData = transform(res);
draft.data = newData;
draft.source = newData;
draft.layoutCache = false;
});
},
updateLayout: res => {
updateState(draft => {
draft.layout = res;
draft.layoutCache = false;
});
},
updateDataAndLayout: (res, lay) => {
updateState(draft => {
const newData = transform(res);
draft.data = newData;
draft.source = newData;
draft.layout = lay;
draft.layoutCache = false;
});
},
// 更新历史记录
updateHistory: param => {
const time = new Date().getTime();
const fn = () => {
updateState(draft => {
// @ts-ignore
draft.history = (draft.history || []).concat([
{
id: createUuid(),
timestamp: time,
...param,
},
]);
});
};
// 防止频繁更新导致的重复 updateHistory
// 同时,间隔一定时间再更新到历史栈中,保证画布数据已经更新完成
if (updateHistoryTimer) clearTimeout(updateHistoryTimer);
updateHistoryTimer = setTimeout(fn, 500);
},
stopForceSimulation: stopForceSimulation,
restartForceSimulation: restartForceSimulation,
};
if (!ComponentAssets) {
return null;
}
const HAS_GRAPH = graphinRef.current?.graph && !graphinRef.current.graph.destroyed;
const { renderComponents, InitializerComponent, InitializerProps, GICC_LAYOUT_COMPONENT, GICC_LAYOUT_PROPS } =
getComponents({ ...state, HAS_GRAPH }, config.components, ComponentAssets);
const graphData = useMemo(() => {
const nodeMap = {};
const edgeMap = {};
const edges: any[] = [];
const nodes: any[] = [];
data.nodes?.forEach(node => {
if (!nodeMap[node.id]) {
nodes.push(node);
nodeMap[node.id] = node;
}
});
data.edges.forEach(edge => {
if (nodeMap[edge.source] && nodeMap[edge.target] && !edgeMap[edge.id]) {
edges?.push(edge);
edgeMap[edge.id] = edge;
}
});
const { combos } = data;
return {
nodes,
edges,
combos,
};
}, [data]);
return (
//@ts-ignore
<GraphInsightContext.Provider value={ContextValue}>
<GICC_LAYOUT_COMPONENT {...GICC_LAYOUT_PROPS}>
<div
id={`${GISDK_ID}-container`}
style={{ width: '100%', height: '100%', position: 'relative', ...props.style }}
>
<Graphin
animate={true}
ref={graphinRef}
containerId={`${GISDK_ID}-graphin-container`}
containerStyle={{ transform: 'scale(1)' }}
data={graphData}
layout={layout}
enabledStack={true}
theme={theme}
layoutCache={state.layoutCache}
style={{ borderRadius: '8px', overflow: 'hidden' }}
willUnmount={() => {
console.log('un mount....');
}}
>
<>
{HAS_GRAPH && <InitializerComponent {...InitializerProps} />}
{HAS_GRAPH && state.initialized && <SizeSensor />}
{/* <SetupUseGraphinHook updateContext={updateState} /> */}
{HAS_GRAPH && state.initialized && renderComponents()}
{HAS_GRAPH && state.initialized && <FitCenterAfterMount />}
{HAS_GRAPH && state.initialized && children}
</>
</Graphin>
</div>
</GICC_LAYOUT_COMPONENT>
</GraphInsightContext.Provider>
);
};
export default React.memo(GISDK);