forked from lkiarest/flow-chart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chart.js
417 lines (365 loc) · 10.8 KB
/
chart.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
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
/**
* @class 流程节点
* @param {Object} container 节点容器(画布),jquery对象
* @param {String} id 节点id
* @param {String} name 节点名称
* @param {Number} x 节点x坐标
* @param {Number} y 节点y坐标
* @param {Object} [options] 节点附加属性
* @param {String} [options.color] 节点文字颜色
* @param {String} [options.bgColor] 节点背景色
* @param {Number} [options.radius] 节点圆角大小
* @param {Number} [options.data] 绑定到节点的附加数据
* @param {Number} [options.container] 节点容器(画布),若设置此选项则会自动将节点添加到画布上
* @param {Boolean} [options.removable=true] 是否支持删除功能(鼠标放上去显示关闭图标)
*/
let ChartNode = function(id, name, x, y, options) {
this._jsPlumb = null;
this._container = null;
this._id = id;
this._name = name;
this._x = x;
this._y = y;
this._clsName = options.class || '';
this._data = options && options.data || {};
this._data.nodeId = id;
this._options = $.extend({ // 默认属性
removable: true
}, options);
this._el = null;
if (options && options.container) {
this.appendTo(options.container);
}
};
/**
* 连线样式
* @type {Object}
*/
ChartNode.lineStyle = {
lineWidth: 1,
joinstyle: "round",
strokeStyle: "#0096f2"
};
/**
* 标签位置
*/
ChartNode.labelPos = {
'Bottom': [6, 2.5],
'Top': [6, -2.5],
};
ChartNode.prototype.setPlumb = function (plumb) {
this._jsPlumb = plumb;
};
ChartNode.prototype._px = (value) => {
return value + 'px';
};
ChartNode.prototype.getId = function() {
return this._id;
};
ChartNode.prototype.getData = function() {
return this._data || {};
};
ChartNode.prototype.appendTo = function(container) {
if (! container) {
console.error('node container is null !');
return;
}
let self = this;
let options = self._options;
let px = self._px;
// 创建并插入 dom 节点
let node = $('<div>').addClass(`window task ${self._clsName}`)
.attr('id', self._id)
.css({
left: px(self._x),
top: px(self._y)
})
.text(self._name)
.data('node', this._data)
.data('__node', this);
if (options.removable) {
let removeIcon = $('<div>').addClass('remove');
node.append(removeIcon);
}
container.append(node);
this._jsPlumb.draggable(node, { grid: [10, 10] });
this._el = node;
};
/**
* 添加连接端口
* @param {Object} options 连接端口参数
* @param {String} [options.color=#0096f2] 端口颜色
* @param {Boolean} [options.isSource=false] 是否为源端口
* @param {Boolean} [options.isTarget=false] 是否为目标端口
* @param {String} [options.label] 端口名称
* @param {String} [options.position=bottom] 端口位置,可设置为 'Top'
*/
ChartNode.prototype.addPort = function(options) {
let pos = options.position || 'Bottom';
let labelPos = ChartNode.labelPos[pos];
let endpointConf = {
endpoint: "Dot",
paintStyle: {
strokeStyle: options.color || '#0096f2',
radius: 2,
lineWidth: 1
},
anchor: pos,
isSource: !!options.isSource,
isTarget: !!options.isTarget,
maxConnections: -1,
connector: ["Flowchart", { stub: [15, 15], gap: 0, cornerRadius: 5, alwaysRespectStubs: true }],
connectorStyle: ChartNode.lineStyle,
// connectorOverlays: [[ "Arrow", {location: 1}]],
// hoverPaintStyle: endpointHoverStyle,
// connectorHoverStyle: connectorHoverStyle,
dragOptions: {},
overlays: [
["Label", {
location: labelPos,
label: options.label || '',
cssClass: "endpoint-label-lkiarest"
}]
],
allowLoopback:false
};
this._jsPlumb.addEndpoint(this._el, endpointConf);
};
/**
* 更新坐标
*/
ChartNode.prototype.updatePos = function() {
let el = this._el;
this._x = parseInt(el.css("left"), 10);
this._y = parseInt(el.css("top"), 10);
};
ChartNode.prototype.getPos = function() {
return {
x: this._x,
y: this._y
};
};
ChartNode.prototype.toPlainObj = function() {
let item = this;
item.updatePos();
let data = $.extend({}, item._data);
data.nodeId = item._id;
data.positionX = item._x;
data.positionY = item._y;
data.className = item._clsName;
data.removable = item._options.removable;
return data;
};
ChartNode.prototype.dispose = function() {
let el = this._el;
let domEl = el.get(0);
this._jsPlumb.detachAllConnections(domEl);
this._jsPlumb.remove(domEl);
el.remove();
};
/**
* @class 画布
*/
let Chart = function(container, options) {
this._jsPlumb = null; // 多实例支持!
this._container = container;
this._nodes = [];
this._seedName = 'flow-chart-node';
this._seedId = 0;
this.init(options);
};
Chart.prototype.nodeId = function() {
return this._seedName + (this._seedId++) + (new Date).valueOf();
};
/**
* 初始化方法
* @param {Object} [options] 初始化参数
* @param {Function} [options.onNodeClick] 节点点击事件回调函数,参数为节点绑定的数据
*/
Chart.prototype.init = function(options) {
this._jsPlumb = jsPlumb.getInstance();
this._jsPlumb.importDefaults({
// DragOptions: { cursor: 'pointer', zIndex: 2000 },
ConnectionOverlays: [
["PlainArrow", {
width: 10,
location: 1,
id: "arrow",
length: 8
}]
],
DragOptions : { cursor: 'pointer', zIndex:2000 },
EndpointStyles : [{ fillStyle:'#225588' }, { fillStyle:'#558822' }],
Endpoints : [ [ "Dot", { radius:2 } ], [ "Dot", { radius: 2 } ]],
Connector:[ "Flowchart", { stub:[15, 25], gap:0, cornerRadius:5, alwaysRespectStubs:true } ],
// ConnectionOverlays : [
// [ "Arrow", {
// location:1,
// id:"arrow",
// length:20,
// foldback:0.4
// } ]
// ]
});
this._container.addClass('flow-chart-canvas-lkiarest');
// 点击事件
if (options && options.onNodeClick) {
this._container.on('click', '.task', event => {
let target = $(event.target);
options.onNodeClick.call(this, target.data('node'));
});
}
// 删除节点
this._container.on('click', '.remove', event => {
let delNode = $(event.target).parent().data('__node');
if (delNode) {
let data = delNode.getData();
let nodeId = delNode.getId();
delNode.dispose();
this.removeNode(nodeId);
if (options && options.onNodeDel) {
options.onNodeDel.call(this, data);
}
}
event.stopPropagation();
});
};
/**
* 添加新节点
* @param {String} name 节点名称
* @param {Number} x 节点x坐标
* @param {Number} y 节点y坐标
* @param {Object} options 节点参数,可参考 {class ChartNode} 构造参数
* @param {String} [options.id] 节点id,若未定义则由系统自动分配
*/
Chart.prototype.addNode = function(name, x, y, options) {
let id = options && options.id || this.nodeId();
let node = new ChartNode(id, name, x, y, options);
node.setPlumb(this._jsPlumb);
node.appendTo(this._container);
this._nodes.push(node);
return node;
};
Chart.prototype.removeNode = function(nodeId) {
let nodes = this._nodes;
for (let i = 0, len = nodes.length; i < len; i++) {
let node = nodes[i];
if (node.getId() === nodeId) {
node.dispose();
nodes.splice(i, 1);
return node;
}
}
};
Chart.prototype.getNodes = function() {
return this._nodes;
};
/**
* 序列化以保存
*/
Chart.prototype.toJson = function() {
// 获取所有节点
let nodes = [];
this._nodes.forEach(item => {
nodes.push(item.toPlainObj());
});
// 获取所有连接
let connections = this._jsPlumb.getConnections().map(connection => {
return {
connectionId: connection.id,
pageSourceId: connection.sourceId,
pageTargetId: connection.targetId
};
});
return {
nodes: nodes,
connections: connections
};
};
/**
* 反序列化保存的数据并绘制流程图
*/
Chart.prototype.fromJson = function(jsonStr) {
if (!jsonStr || jsonStr === '') {
console.error('draw from json failed: empty json string');
reutrn;
}
let jsonObj = null;
try {
jsonObj = JSON.parse(jsonStr);
} catch (e) {
console.error('invalid json string', e);
return;
}
this.clear();
let nodes = jsonObj.nodes;
let connections = jsonObj.connections;
nodes && nodes.forEach(item => {
let node = this.addNode(item.name, item.positionX, item.positionY, {
class: item.className,
removable: item.removable,
id: item.nodeId,
data: item
});
switch(item.className) {
case 'node-start': {
node.addPort({
isSource: true
});
break;
}
case 'node-end': {
node.addPort({
isTarget: true,
position: 'Top'
});
break;
}
default: {
node.addPort({
isSource: true
});
node.addPort({
isTarget: true,
position: 'Top'
});
}
}
this._jsPlumb.repaint(node.getId());
});
connections && connections.forEach(item => {
this._jsPlumb.connect({
source: item.pageSourceId,
target: item.pageTargetId,
deleteEndpointsOnDetach:false,
paintStyle: ChartNode.lineStyle,
anchors: ["Bottom", [0.5, 0, 0, -1]]
});
});
this._jsPlumb.repaintEverything();
};
/**
* 清除画布中的元素
*/
Chart.prototype.clear = function() {
this._nodes && this._nodes.forEach(item => {
item.dispose();
});
this._nodes = [];
this._jsPlumb.detachAllConnections(this._container);
this._jsPlumb.removeAllEndpoints(this._container);
};
/**
* 销毁释放
*/
Chart.prototype.dispose = function () {
this.clear();
this._container.off('click'); // unbind events
this._container = null;
};
Chart.ready = (callback) => {
jsPlumb.ready(callback);
};
if (typeof module === 'object' && module && typeof module.exports === 'object') {
module.exports = Chart;
}