-
Notifications
You must be signed in to change notification settings - Fork 12
/
Visualizer.js
752 lines (670 loc) · 23 KB
/
Visualizer.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
import _ from 'lodash';
import joint, { V } from 'jointjs';
import Workflow from '../model/Workflow';
import Declaration from '../model/Declaration';
import Port from '../model/Port';
import Paper from './Paper';
import VisualLink from './VisualLink';
import VisualStep from './VisualStep';
import VisualGroup from './VisualGroup';
import VisualWorkflow from './VisualWorkflow';
import VisualDeclaration from './VisualDeclaration';
import Zoom from './Zoom';
// Code below is an official fix for Chrome 57 from JointJS
V.matrixToTransformString = (matrix) => {
matrix = matrix || true;
return `matrix(${[matrix.a || 1, matrix.b || 0, matrix.c || 0, matrix.d || 1, matrix.e || 0, matrix.f || 0]})`;
};
V.prototype.transform = function fun(matrix, opt) {
const node = this.node;
if (V.isUndefined(matrix)) {
return (node.parentNode)
? this.getTransformToElement(node.parentNode)
: node.getScreenCTM();
}
if (opt && opt.absolute) {
return this.attr('transform', V.matrixToTransformString(matrix));
}
const svgTransform = V.createSVGTransform(matrix);
node.transform.baseVal.appendItem(svgTransform);
return this;
};
function createVisual(opts) {
if (opts.step instanceof Workflow) {
return new VisualWorkflow(opts);
} else if (!_.isUndefined(opts.step.type)) {
return new VisualGroup(opts);
}
return new VisualStep(opts);
}
function getDescendants(cell, currDepth) {
const embeds = cell.getEmbeddedCells();
let best = { cell, currDepth };
_.forEach(embeds, (child) => {
const chBest = getDescendants(child, currDepth + 1);
if (chBest.currDepth > best.currDepth) {
best = chBest;
}
});
return best;
}
function getHighestDescendant(cell) {
return getDescendants(cell, 0).cell;
}
function createSubstituteCells(graph) {
const newCellsMap = graph.cloneCells(graph.getCells());
const newCells = [];
let cellIdx = 0;
_.forEach(newCellsMap, (newCell, key) => {
const cellProto = graph.getCell(key);
if (newCell.isLink()) {
const protoSrc = cellProto.getSourceElement();
const protoDst = cellProto.getTargetElement();
if (protoDst.isEmbeddedIn(protoSrc, { deep: true }) ||
protoSrc.isEmbeddedIn(protoDst, { deep: true })) {
return;
}
const source = newCellsMap[getHighestDescendant(protoSrc).id];
const target = newCellsMap[getHighestDescendant(protoDst).id];
newCell.get('source').id = source.id;
newCell.get('target').id = target.id;
} else {
const bbox = cellProto.getBBox();
newCell.set('size', {
width: bbox.width,
height: bbox.height,
});
}
newCells[cellIdx] = newCell;
cellIdx += 1;
newCell.proto = cellProto;
});
const gr = new joint.dia.Graph();
gr.addCells(newCells);
return gr;
}
function generateChildName(step) {
let parentName = null;
if (step.parent) {
parentName = generateChildName(step.parent);
}
return parentName ? `${parentName}_${step.name}` : step.name;
}
class VisualWorkflowView extends joint.dia.ElementView {
pointerdown(evt, x, y) {
if (evt.target.getAttribute('magnet') && evt.which === 1 && evt.shiftKey) {
const port = evt.target.getAttribute('port');
const isIn = evt.target.getAttribute('port-group') === 'in';
this.model.togglePort(isIn, port);
this._dx = x;
this._dy = y;
evt.stopPropagation();
} else {
super.pointerdown(evt, x, y);
}
}
}
/**
* Class that allows to work with graphical pipeline representation.
*
* @example
* const flow = new Workflow(...);
* const diagram = new Visualizer(document.getElementById('diagram'));
* diagram.attachTo(flow);
*/
export default class Visualizer {
/**
* Create a pipeline visualizer.
* @param {Element|string} element - DOM Element or its identifier to embed the visualizer into.
* @param {boolean} readOnly - specify the read only access mode
*/
constructor(element, readOnly = false) {
const graph = new joint.dia.Graph();
if (!(element instanceof Element)) {
element = document.getElementById(element);
}
this._readOnly = readOnly;
const paper = new Paper({
el: element,
width: element.offsetWidth,
height: element.offsetHeight,
model: graph,
defaultLink: new VisualLink(),
elementView: VisualWorkflowView,
interactive: val => !this._elementsPanning && (!this._readOnly || !(val.model instanceof VisualLink)),
clickThreshold: 1,
});
/**
* JointJS paper object.
* @type {joint.dia.Paper}
*/
this.paper = paper;
/**
* Array of currently selected states.
* @type {Array}
*/
this.selection = [];
/** Public member to access zoom object
* @type {Zoom}
*/
this.zoom = new Zoom(paper);
this._dragStartPosition = null;
this._elementsPanning = false;
this._handlePanning();
this._handleSelection();
this._selectionEnabled = true;
this._graph = graph;
this._children = {};
this._declarations = {};
this._timer = null;
this._step = null;
this.clear();
const validateMagnet = this.paper.options.validateMagnet;
this.paper.options.validateMagnet = (cellView, magnet) => {
if (this._readOnly) {
return false;
}
const args = [cellView, magnet];
return validateMagnet.apply(this.paper, args);
};
const validateConnection = this.paper.options.validateConnection;
this.paper.options.validateConnection = (cellViewS, magnetS, cellViewT, magnetT, end, linkView) => {
if (this._readOnly) {
return false;
}
if (this._isChildSubWorkflow(cellViewS.model.step)) return false;
if (this._isChildSubWorkflow(cellViewT.model.step)) return false;
const args = [cellViewS, magnetS, cellViewT, magnetT, end, linkView];
if (!validateConnection.apply(this.paper, args)) {
return false;
}
const source = cellViewS.model;
const target = cellViewT.model;
const sourceIsAncestor = target.isEmbeddedIn(source, { deep: true });
const targetIsAncestor = source.isEmbeddedIn(target, { deep: true });
const sourcePortIsInput = magnetS.getAttribute('port-group') === 'in';
const targetPortIsInput = magnetT.getAttribute('port-group') === 'in';
// one may only link step's input if it is an ancestor
// and it is connected to descendants input
if (sourcePortIsInput && (!sourceIsAncestor || !targetPortIsInput)) {
return false;
}
// output port may only be a target port if the source port
// is the target port of a descendant
if (!targetPortIsInput && (!targetIsAncestor || sourcePortIsInput)) {
return false;
}
// one may not connect ancestor's/descendant's output
// with descendant's/ancestor's input
if ((sourceIsAncestor || targetIsAncestor) && !sourcePortIsInput && targetPortIsInput) {
return false;
}
const targetStep = target.step;
const targetPortName = magnetT.attributes.port.value;
const targetGroup = targetPortIsInput ? targetStep.i : targetStep.o;
return _.size(targetGroup[targetPortName].inputs) === 0;
};
graph.on('change:position', (cell) => {
let parentId = cell.get('parent');
while (parentId) {
const parent = graph.getCell(parentId);
parent.fit();
parentId = parent.get('parent');
}
});
}
/**
* Clear the contents of component.
*/
clear() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
this._graph.off('remove', null, this);
this._graph.off('add', null, this);
this._graph.clear();
this._children = {};
this._declarations = {};
this._step = null;
this.selection = [];
}
/**
* Enables selection.
*/
enableSelection() {
this._selectionEnabled = true;
}
/**
* Disables selection
*/
disableSelection() {
this._selectionEnabled = false;
this._clearSelection();
}
/**
* Attaches visualizer component to specific step.
* All step's children are rendered upon attachment.
* @param step
*/
attachTo(step) {
this.clear();
// add all step children to the diagram
this._step = step;
this._update();
this.layout();
this._update();// call update once more to invoke fitEmbeds
this.zoom.fitToPage({ padding: 10, maxScale: 1 });
this._timer = setInterval(() => this._update(), 30);
this._listenLinks();
}
/**
* Layout the contents automatically.
*/
layout() {
const newCells = createSubstituteCells(this._graph);
const settings = {
marginX: 100,
marginY: 10,
rankSep: 100,
nodeSep: 80,
rankDir: 'LR',
setLinkVertices: false,
resizeClusters: true,
setPosition: (element, glNode) => {
element.proto.set('position', {
x: glNode.x - glNode.width / 2,
y: glNode.y - glNode.height / 2 });
}, // setVertices is ignored
};
joint.layout.DirectedGraph.layout(newCells, settings);
}
/**
* Toggles ports on a diagram depending on the onlyTopLevel flag value
*
* @param {boolean} onlyTopLevel - if true applies changes only to the top level step attached
* @param {boolean}[value] - optional value to set
*/
togglePorts(onlyTopLevel, value) {
const groupToEdit = onlyTopLevel ? [this._children[generateChildName(this._step)]] : this._children;
_.forEach(groupToEdit, (child) => {
_.forOwn(child.step.i, (port, name) => child.togglePort(true, name, value));
_.forOwn(child.step.o, (port, name) => child.togglePort(false, name, value));
});
}
get _connectionProcessors() {
return {
declarationToDeclaration: (conn, visDeclaration, links, cellsToAdd) => {
const declarations = this._declarations;
const targetName = conn.to.name;
if (declarations[targetName] &&
_.find(links, link => link.conn === conn) === undefined &&
declarations[targetName].isPortEnabled(conn.to.step.hasInputPort(conn.to), conn.to.name)) {
const isReadOnly = this._readOnly || this._isChildSubWorkflow(visDeclaration.declaration.step) ||
this._isChildSubWorkflow(declarations[targetName].step);
cellsToAdd[cellsToAdd.length] = new VisualLink({
source: {
id: visDeclaration.id,
},
target: {
id: declarations[targetName].id,
},
conn,
}, isReadOnly);
}
},
declarationToPort: (conn, visDeclaration, links, cellsToAdd) => {
const children = this._children;
const targetName = generateChildName(conn.to.step);
if (children[targetName] &&
_.find(links, link => link.conn === conn) === undefined &&
children[targetName].isPortEnabled(conn.to.step.hasInputPort(conn.to), conn.to.name)) {
const isReadOnly = this._readOnly || this._isChildSubWorkflow(visDeclaration.declaration.step) ||
this._isChildSubWorkflow(children[targetName].step);
cellsToAdd[cellsToAdd.length] = new VisualLink({
source: {
id: visDeclaration.id,
},
target: {
id: children[targetName].id,
port: conn.to.name,
},
conn,
}, isReadOnly);
}
},
portToDeclaration: (conn, port, source, links, cellsToAdd) => {
const declarations = this._declarations;
const targetDeclarationName = conn.to.name;
if (declarations[targetDeclarationName] &&
_.find(links, link => link.conn === conn) === undefined &&
declarations[targetDeclarationName].isPortEnabled()) {
const isReadOnly = this._readOnly || this._isChildSubWorkflow(source.step) ||
this._isChildSubWorkflow(declarations[targetDeclarationName].declaration.step);
cellsToAdd[cellsToAdd.length] = new VisualLink({
source: {
id: source.id,
port: port.name,
},
target: {
id: declarations[targetDeclarationName].id,
},
conn,
}, isReadOnly);
}
},
portToPort: (conn, port, source, links, cellsToAdd) => {
const children = this._children;
const targetName = generateChildName(conn.to.step);
if (children[targetName] &&
_.find(links, link => link.conn === conn) === undefined &&
children[targetName].isPortEnabled(conn.to.step.hasInputPort(conn.to), conn.to.name)) {
const isReadOnly = this._readOnly || this._isChildSubWorkflow(source.step) ||
this._isChildSubWorkflow(children[targetName].step);
cellsToAdd[cellsToAdd.length] = new VisualLink({
source: {
id: source.id,
port: port.name,
},
target: {
id: children[targetName].id,
port: conn.to.name,
},
conn,
}, isReadOnly);
}
},
};
}
_loopPorts(ports, source, visDeclarations, cellsToAdd, isEnabled) {
const links = this._graph.getConnectedLinks(source);
_.forEach(ports, (port) => {
if (!isEnabled(port.name)) {
return;
}
_.forEach(port.outputs, (conn) => {
if (conn.to instanceof Declaration) {
this._connectionProcessors
.portToDeclaration(conn, port, source, links, cellsToAdd);
} else if (conn.to instanceof Port) {
this._connectionProcessors
.portToPort(conn, port, source, links, cellsToAdd);
}
});
});
}
_loopDeclarations(visDeclarations, cellsToAdd) {
_.forEach(visDeclarations, (visDeclaration) => {
const links = this._graph.getConnectedLinks(visDeclaration);
_.forEach(visDeclaration.declaration.outputs, (conn) => {
if (conn.to instanceof Declaration) {
this._connectionProcessors
.declarationToDeclaration(conn, visDeclaration, links, cellsToAdd);
} else if (conn.to instanceof Port) {
this._connectionProcessors
.declarationToPort(conn, visDeclaration, links, cellsToAdd);
}
});
});
}
_update() {
const step = this._step;
if (!step) {
return;
}
// validate call <-> step correspondence
const children = this._children;
const declarations = this._declarations;
// handle the renames
const pickBy = _.pickBy || _.pick; // be prepared for legacy lodash 3.10.1
const renamed = pickBy(children, (vStep, name) => name !== generateChildName(vStep.step));
_.forEach(renamed, (vStep, oldName) => {
delete children[oldName];
children[generateChildName(vStep.step)] = vStep;
});
const toRemove = [];
const findChildInModel = (visChild, name, modelChild) => {
const modelChildName = generateChildName(modelChild);
if (modelChildName === name) {
return true;
}
const modelChildren = modelChild.children;
if (_.has(modelChildren, name)) {
return true;
}
let res = false;
_.forEach(modelChildren, (child) => {
res = res || findChildInModel(visChild, name, child);
});
return res;
};
_.forEach(children, (visChild, name) => {
if (!findChildInModel(visChild, name, step)) {
// remove visual step from graph
toRemove[toRemove.length] = visChild;
}
});
this._graph.removeCells(toRemove);
_.forEach(toRemove, (child) => {
const idx = _.indexOf(this.selection, child);
if (idx !== -1) {
this.selection.splice(idx, 1);
}
delete children[generateChildName(child.step)];
});
const cellsToAdd = [];
const updateOrCreateVisualSteps = (innerStep, parent = null) => {
const name = generateChildName(innerStep);
let visChild = children[name];
if (!visChild) {
const opts = this.zoom.fromWidgetToLocal({
x: this.paper.el.offsetWidth / 2,
y: this.paper.el.offsetHeight / 2,
});
opts.step = innerStep;
visChild = createVisual(opts);
children[name] = visChild;
cellsToAdd[cellsToAdd.length] = visChild;
if (_.size(opts.step.ownDeclarations)) {
_.forEach(opts.step.ownDeclarations, (declaration) => {
let visDeclaration = declarations[declaration.name];
if (!visDeclaration) {
visDeclaration = new VisualDeclaration({ declaration, x: opts.x, y: opts.y });
cellsToAdd[cellsToAdd.length] = visDeclaration;
declarations[declaration.name] = visDeclaration;
visChild.embed(visDeclaration);
visChild.fit();
visChild.update();
}
});
}
if (parent) {
parent.embed(visChild);
parent.fit();
parent.update();
}
} else {
// it is essential to update links before the step!
const links = this._graph.getConnectedLinks(visChild);
_.forEach(links, (link) => {
link.refresh();
});
visChild.update();
}
const innerChildren = innerStep.children;
_.forEach(innerChildren, (child) => {
updateOrCreateVisualSteps(child, visChild);
});
};
updateOrCreateVisualSteps(step);
_.forEach(children, (child) => {
this._loopPorts(child.step.o, child, declarations, cellsToAdd, portName => child.isPortEnabled(false, portName));
this._loopPorts(child.step.i, child, declarations, cellsToAdd, portName => child.isPortEnabled(true, portName));
});
this._loopDeclarations(declarations, cellsToAdd);
this._graph.addCells(cellsToAdd);
}
_listenLinks() {
const graph = this._graph;
graph.on('remove', (cell, child, opts) => {
if (this._readOnly) {
return;
}
if (cell instanceof VisualLink && cell.conn && cell.conn.isValid() && !opts.silent) {
cell.conn.unbind();
}
}, this);
graph.on('change:source change:target', (link) => {
if (this._readOnly) {
return;
}
if (link instanceof VisualLink) {
const source = graph.getCell(link.get('source').id);
const target = graph.getCell(link.get('target').id);
if (!(source instanceof VisualStep) || !(target instanceof VisualStep)) {
return;
}
if (!source.step || !target.step) {
return;
}
const sourceChild = source.step;
const targetChild = target.step;
if (link.conn) {
link.conn.unbind();
}
if (!targetChild || !sourceChild) {
return;
}
const srcPortName = link.get('source').port;
const sourcePort = this.paper.findViewByModel(link).sourceMagnet.getAttribute('port-group') === 'in' ?
sourceChild.i[srcPortName] :
sourceChild.o[srcPortName];
const dstPortName = link.get('target').port;
const targetPort = this.paper.findViewByModel(link).targetMagnet.getAttribute('port-group') === 'in' ?
targetChild.i[dstPortName] :
targetChild.o[dstPortName];
link.conn = targetPort.bind(sourcePort);
}
}, this);
}
_clearSelection() {
_.forEach(this.selection, (elem) => {
V(this.paper.findViewByModel(elem).el).toggleClass('selected', false);
});
this.selection = [];
}
_handleSelection() {
this.paper.on('blank:pointerclick', () => {
if (!this._selectionEnabled) {
return;
}
this._clearSelection();
});
this.paper.on('cell:pointerclick', (view, evt) => {
if (!this._selectionEnabled) {
return;
}
const model = view.model;
if (model instanceof VisualStep) {
if (evt.shiftKey) { // if shift key is pressed - group selection
const idx = _.indexOf(this.selection, model);
// toggle the selection of current element
if (idx !== -1) {
this.selection.splice(idx, 1);
} else {
this.selection.push(model);
}
} else {
// clear selection and mark element as the only selected
this._clearSelection();
this.selection.push(model);
}
view.$el.toggleClass('selected');
}
});
}
/**
* Toggles elements panning mode
* (If it's turned on then you can pan whole Paper dragging on any element)
* */
togglePanningMode() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
if (this._elementsPanning) {
this._turnOffElementsPanning();
if (this._readOnlyDump && this._readOnlyDump.length) {
this._readOnly = this._readOnlyDump[0];
}
} else {
this._turnOnElementsPanning();
if (!this._readOnly) {
this._readOnlyDump = [this._readOnly];
this._readOnly = true;
}
}
this._timer = setInterval(() => this._update(), 30);
}
_turnOffElementsPanning() {
const paper = this.paper;
paper.off('cell:pointerdown', this._setCellDragStartPosition);
paper.off('cell:pointerup', this._clearDragStartPosition);
_.forEach(this._graph.getCells(), (cell) => {
V(this.paper.findViewByModel(cell).el).toggleClass('pannable', false);
});
this._elementsPanning = false;
}
_turnOnElementsPanning() {
const paper = this.paper;
paper.on('cell:pointerdown', this._setCellDragStartPosition, this);
paper.on('cell:pointerup', this._clearDragStartPosition, this);
_.forEach(this._graph.getCells(), (cell) => {
V(this.paper.findViewByModel(cell).el).toggleClass('pannable', true);
});
this._elementsPanning = true;
}
_setCellDragStartPosition(cellView, event, x, y) {
this.paper.$el.find('svg').toggleClass('is-panning', true);
this._dragStartPosition = { x, y };
}
_clearDragStartPosition() {
this.paper.$el.find('svg').toggleClass('is-panning', false);
this._dragStartPosition = null;
}
_handlePanning() {
const paper = this.paper;
paper.$el.find('svg').toggleClass('pannable', true);
paper.on('blank:pointerdown', (event, x, y) => {
this._dragStartPosition = { x, y };
paper.$el.find('svg').toggleClass('is-panning', true);
});
if (this._elementsPanning) {
paper.on('cell:pointerdown', this._setCellDragStartPosition, this);
paper.on('cell:pointerup', this._clearDragStartPosition, this);
}
paper.on('blank:pointerup', () => {
this._clearDragStartPosition();
});
paper.el.onmousemove = (event) => {
const currScale = this.zoom.getCurrentScale();
if (this._dragStartPosition) {
paper.setOrigin(
event.offsetX - (this._dragStartPosition.x * currScale),
event.offsetY - (this._dragStartPosition.y * currScale));
}
};
window.onresize = () => {
const elem = paper.el;
if (!elem) {
return;
}
paper.setDimensions(elem.offsetWidth, elem.offsetHeight);
};
}
_isChildSubWorkflow(step) {
if (!step || !step.parent) return false;
if (step.parent instanceof Workflow && step.parent.name !== this._step.name) return true;
return this._isChildSubWorkflow(step.parent);
}
}