-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathlinkConfig.js
More file actions
638 lines (576 loc) · 20.2 KB
/
linkConfig.js
File metadata and controls
638 lines (576 loc) · 20.2 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
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
import { dia, linkTools } from 'jointjs';
import get from 'lodash/get';
import debounce from 'lodash/debounce';
import { invalidNodeColor, setShapeColor, validNodeColor } from '@/components/nodeColors';
import { getDefaultAnchorPoint } from '@/portsUtils';
import resetShapeColor from '@/components/resetShapeColor';
import store from '@/store';
import {
removeOutgoingAndIncomingRefsToFlow,
} from '@/components/crown/utils';
import {
COLOR_IDLE,
COLOR_COMPLETED,
} from '@/components/highlightColors.js';
const endpoints = {
source: 'source',
target: 'target',
};
function isPoint(item) {
return item.x && item.y;
}
export default {
props: ['highlighted', 'paper', 'paperManager', 'isCompleted', 'isIdle'],
data() {
return {
linkView: null,
sourceShape: null,
target: null,
listeningToMouseup: false,
listeningToMouseleave: false,
vertices: null,
anchorPointFunction: getDefaultAnchorPoint,
onChangeWasFired: false,
};
},
watch: {
target(target, previousTarget) {
if (previousTarget && previousTarget !== target) {
resetShapeColor(previousTarget);
}
},
isValidConnection(isValid) {
if (isValid) {
this.shape.stopListening(this.paper, 'blank:pointerdown link:pointerdown element:pointerdown', this.removeLink);
} else {
this.shape.listenToOnce(this.paper, 'blank:pointerdown link:pointerdown element:pointerdown', this.removeLink);
}
},
highlighted(highlighted) {
if (store.getters.isReadOnly) {
return;
}
if (highlighted) {
this.shape.attr({
line: { stroke: '#5096db' },
'.joint-highlight-stroke': { 'display': 'none' },
});
this.shapeView.showTools();
} else {
resetShapeColor(this.shape);
this.shapeView.hideTools();
}
},
},
computed: {
shapeView() {
return this.shape.findView(this.paper);
},
sourceNode() {
return get(this.sourceShape, 'component.node');
},
targetNode() {
return get(this.target, 'component.node');
},
sourceConfig() {
return this.sourceNode && this.nodeRegistry[this.sourceNode.type];
},
targetConfig() {
return this.targetNode && this.nodeRegistry[this.targetNode.type];
},
elementPadding() {
return this.shape && this.shape.source().id === this.shape.target().id ? 20 : 1;
},
},
methods: {
setHighlightColor(highlighted, color) {
if (highlighted) {
this.shape.attr({
line: { stroke: color },
'.joint-highlight-stroke': { 'display': 'none' },
});
this.shapeView.showTools();
} else {
resetShapeColor(this.shape);
this.shapeView.hideTools();
}
},
setShapeHighlight() {
if (this.isCompleted) {
this.shape.attr({
line: { stroke: COLOR_COMPLETED },
});
}
else if (this.isIdle) {
this.shape.attr({
line: { stroke: COLOR_IDLE },
});
}
},
findSourceShape() {
return this.graph.getElements().find(element => {
return element.component && element.component.node.definition === this.node.definition.get('sourceRef');
});
},
setEndpoint(shape, endpoint, connectionOffset) {
if (shape && isPoint(shape)) {
return this.shape[endpoint](shape, {
anchor: {
name: 'modelCenter',
args: { padding: 25 },
},
connectionPoint: { name: 'boundary' },
});
}
const getConnectionPoint = () => {
const { x, y } = shape.position();
const { width, height } = shape.size();
return connectionOffset
? { x: x + connectionOffset.x, y: y + connectionOffset.y }
: { x: x + (width / 2), y: y + (height / 2) };
};
this.shape[endpoint](shape, {
anchor: () => {
return this.getAnchorPointFunction(endpoint)(getConnectionPoint(), shape.findView(this.paper));
},
connectionPoint: { name: 'boundary' },
});
},
setSource(sourceShape, connectionPoint) {
this.setEndpoint(sourceShape, endpoints.source, connectionPoint);
},
setTarget(targetShape, connectionPoint) {
this.setEndpoint(targetShape, endpoints.target, connectionPoint);
},
/**
* Completes the link setup by stopping event listeners, resetting events,
* setting up shape listeners, embedding the source shape, and storing the initial target.
*/
completeLink() {
this.stopListeningToEvents();
this.resetAndEmitEvents();
const targetShape = this.getAndResetTargetShape();
this.setupShapeListeners(targetShape);
this.embedAndEmitSourceShape();
this.storeInitialTarget();
},
/**
* Stops listening to specific events on the shape.
*/
stopListeningToEvents() {
this.shape.stopListening(this.paper, 'cell:mouseleave');
},
/**
* Resets the paper and emits an event to set the cursor to null.
*/
resetAndEmitEvents() {
this.$emit('set-cursor', null);
this.resetPaper();
},
/**
* Retrieves the target shape, resets its color, and returns it.
* @returns {Object} The target shape.
*/
getAndResetTargetShape() {
const targetShape = this.shape.getTargetElement();
resetShapeColor(targetShape);
return targetShape;
},
/**
* Sets up listeners for changes in vertices, source, target, and position of shapes.
* @param {Object} targetShape - The target shape to listen to.
*/
setupShapeListeners(targetShape) {
this.shape.on('change:vertices', this.onChangeVertices);
this.shape.on('change:source', this.onChangeSource);
this.shape.on('change:target', this.onChangeTarget);
this.shape.listenTo(this.sourceShape, 'change:position', this.updateWaypoints);
this.shape.listenTo(targetShape, 'change:position', this.updateWaypoints);
this.shape.listenTo(this.paper, 'link:mouseleave', this.storeWaypoints);
this.shape.listenTo(this.paper, 'link:pointerup', this.pointerUpHandler);
},
// Define the pointerUpHandler function
pointerUpHandler(linkView) {
// Check if the link is completed
const linkModel = linkView.model;
const source = linkModel.get('source');
const target = linkModel.get('target');
// Check if the link has both a source and a target
if (source.id && target.id) {
// Provide options or perform actions
this.showLinkOptions(linkView);
} else {
this.revertToPreviousTarget();
}
},
// Function to show options when a link is completed
showLinkOptions(linkView) {
// Example: Display a dialog or menu with options
console.log('Link completed:', linkView.model);
this.completeLink();
// Implement your logic to show options here
},
/**
* Embeds the source shape into the current shape and emits an event to set shape stacking.
*/
embedAndEmitSourceShape() {
const sourceShape = this.shape.getSourceElement();
sourceShape.embed(this.shape);
this.$emit('set-shape-stacking', sourceShape);
},
/**
* Stores the initial target of the shape for future reference.
*/
storeInitialTarget() {
this.shape.set('initialTarget', this.shape.get('target'));
},
waitForUpdateWaypoints() {
return new Promise(resolve => {
this.updateWaypoints();
this.updateWaypoints.flush();
resolve();
});
},
async storeWaypoints() {
if (this.highlighted && !this.listeningToMouseleave) {
this.updateWaypoints();
await this.$nextTick();
if (this.$parent.isMultiplayer && this.linkView) {
// update waypoints in multiplayer mode
const nodeType = this.linkView.model.component.node.type;
const sourceRefId = this.linkView.sourceView.model.component.node.definition.id;
const targetRefId = this.linkView.targetView.model.component.node.definition.id;
const changes = [
{
id: this.linkView.model.component.node.definition.id,
properties: {
type: nodeType,
waypoint: [
this.linkView.sourceAnchor.toJSON(),
...this.shape.vertices(),
this.linkView.targetAnchor.toJSON(),
],
sourceRefId,
targetRefId,
},
},
];
window.ProcessMaker.EventBus.$emit('multiplayer-updateNodes', changes);
}
this.listeningToMouseleave = true;
this.$emit('save-state');
}
},
/**
* Handles the pointer up event.
* Performs actions based on changes in the target shape.
* @async
*/
async handleTargetChange(link) {
const targetNode = this.paper.findViewByModel(link.get('target').id).model.component.node;
const targetConfig = targetNode && this.nodeRegistry[targetNode.type];
const isValid = this.validateConnection(targetConfig);
if (isValid) {
await this.processValidTargetChange(link);
} else {
this.revertToPreviousTarget();
}
},
validateConnection(targetConfig) {
return this.isValid?.({
sourceShape: this.sourceShape,
targetShape: this.currentTarget,
targetConfig,
});
},
async processValidTargetChange(link) {
const targetModel = this.paper.findViewByModel(link.get('target').id).model;
removeOutgoingAndIncomingRefsToFlow(this.node);
this.target = targetModel;
if (this.updateDefinitionLinks) {
this.updateDefinitionLinks();
}
this.listeningToMouseleave = true;
await this.storeWaypoints();
this.emitMultiplayerUpdateFlows();
},
revertToPreviousTarget() {
this.setTarget(this.target);
},
setTargetWithAnchorOffset() {
this.setTarget(this.target, this.getAnchorOffset());
},
emitMultiplayerUpdateFlows() {
const waypoint = this.node.diagram.waypoint?.map(point => ({
x: point.x,
y: point.y,
})) || [];
window.ProcessMaker.EventBus.$emit('multiplayer-updateFlows', [
{
id: this.node.definition.id,
type: this.node.type,
name: this.node.definition.name,
waypoint,
sourceRefId: this.node.definition.sourceRef.id,
targetRefId: this.node.definition.targetRef.id,
},
]);
},
/**
* Calculates the offset between the target anchor point and the position of the target element.
*
* @returns {Object} An object representing the offset with 'x' and 'y' properties.
*/
getAnchorOffset() {
// Get the waypoints of the sequence flow
const sequenceFlowWaypoints = this.node.diagram.waypoint;
// Get the last waypoint, which is the target anchor point
const targetAnchorPoint = sequenceFlowWaypoints[sequenceFlowWaypoints.length - 1];
// Get the position (x, y) of the target element
const { x: targetX, y: targetY } = this.target.position();
// Calculate and return the offset between the target anchor point and the target element position
return {
x: targetAnchorPoint.x - targetX,
y: targetAnchorPoint.y - targetY,
};
},
/**
* Handles changes in source shapes for a link.
* @async
* @param {Vertices} vertices - The new vertices information.
* @param {Object} options - Additional options.
*/
async onChangeSource(vertices, options) {
if (options?.ui && vertices.id) {
await this.handleWaypointUpdate();
}
},
/**
* Handles changes in target shapes for a link.
* @async
* @param {Object} link - The link object.
* @param {Vertices} vertices - The new vertices information.
* @param {Object} options - Additional options.
*/
async onChangeTarget(link, vertices, options) {
const initialTarget = link.get('initialTarget');
const currentTarget = link.get('target');
// Check if the target has changed to another
if (options?.ui && vertices.id) {
if (this.isTargetChanged(currentTarget, initialTarget)) {
await this.handleTargetChange(link);
link.set('initialTarget', currentTarget);
} else {
await this.handleWaypointUpdate();
}
}
},
/**
* Checks if the target has changed by comparing the current target with the initial target.
* @param {Object} currentTarget - The current target object.
* @param {Object} initialTarget - The initial target object.
* @returns {boolean} - Returns true if the target has changed, otherwise false.
*/
isTargetChanged(currentTarget, initialTarget) {
return currentTarget.id && currentTarget.id !== initialTarget.id;
},
/**
* Handles the update of waypoints.
* @async
*/
async handleWaypointUpdate() {
try {
console.log('handleWaypointUpdate');
await this.$nextTick();
await this.waitForUpdateWaypoints();
this.listeningToMouseleave = false;
await this.storeWaypoints();
} catch (error) {
console.error('Error in handleWaypointUpdate:', error);
}
},
async onChangeVertices(link, vertices, options) {
if (options?.ui) {
this.updateWaypoints();
await this.$nextTick();
this.listeningToMouseleave = false;
this.$emit('save-state');
}
},
updateWaypoints() {
this.linkView = this.shape.findView(this.paper);
const start = this.linkView.sourceAnchor;
const end = this.linkView.targetAnchor;
this.node.diagram.waypoint = [start,
...this.shape.vertices(),
end].map(point => this.moddle.create('dc:Point', point));
if (!this.listeningToMouseup) {
this.listeningToMouseup = true;
document.addEventListener('mouseup', this.emitSave);
}
},
updateLinkTarget({ clientX, clientY }) {
const localMousePosition = this.paper.clientToLocalPoint({ x: clientX, y: clientY });
/* Sort shapes by z-index descending; grab the shape on top (with the highest z-index) */
this.target = this.graph.findModelsFromPoint(localMousePosition).sort((shape1, shape2) => {
return shape2.get('z') - shape1.get('z');
})[0];
if (!this.isValidConnection) {
this.$emit('set-cursor', 'not-allowed');
this.shape.target({
x: localMousePosition.x,
y: localMousePosition.y,
});
if (this.target) {
setShapeColor(this.target, invalidNodeColor);
}
return;
}
this.setTarget(this.target);
this.updateRouter();
this.$emit('set-cursor', 'default');
setShapeColor(this.target, validNodeColor);
this.paper.el.removeEventListener('mousemove', this.updateLinkTarget);
this.shape.listenToOnce(this.paper, 'cell:pointerclick', () => {
this.completeLink();
this.updateWaypoints();
this.updateWaypoints.flush();
if (this.updateDefinitionLinks) {
this.updateDefinitionLinks();
}
if (this.linkView && ['processmaker-modeler-association', 'processmaker-modeler-data-input-association'].includes(this.shape.component.node.type)) {
this.$parent.multiplayerHook(this.shape.component.node, false);
}
this.$emit('save-state');
});
this.shape.listenToOnce(this.paper, 'cell:mouseleave', () => {
this.paper.el.addEventListener('mousemove', this.updateLinkTarget);
this.shape.stopListening(this.paper, 'cell:pointerclick');
resetShapeColor(this.target);
this.$emit('set-cursor', 'not-allowed');
});
},
removeLink() {
this.$emit('remove-node', this.node);
this.resetPaper();
},
resetPaper() {
this.$emit('set-cursor', null);
this.paper.el.removeEventListener('mousemove', this.updateLinkTarget);
this.paper.setInteractivity(this.graph.get('interactiveFunc'));
if (this.target) {
resetShapeColor(this.target);
}
},
getAnchorPointFunction(endpoint) {
if (endpoint === 'source') {
return this.sourceShape.component.anchorPointFunction || this.anchorPointFunction;
}
if (endpoint === 'target') {
return this.target.component.anchorPointFunction || this.anchorPointFunction;
}
},
setupLinkTools() {
const verticesTool = new linkTools.Vertices();
const sourceAnchorTool = new linkTools.SourceAnchor({ snap: this.getAnchorPointFunction('source') });
const targetAnchorTool = new linkTools.TargetAnchor({ snap: this.getAnchorPointFunction('target') });
let toolsView = new dia.ToolsView({
tools: [verticesTool, sourceAnchorTool, targetAnchorTool],
});
if (this.shape.component.node.type === 'processmaker-modeler-sequence-flow') {
toolsView = new dia.ToolsView({
tools: [verticesTool, sourceAnchorTool, targetAnchorTool, new linkTools.TargetArrowhead()],
});
}
this.currentTarget = this.shape.getTargetElement();
this.shapeView.addTools(toolsView);
this.shapeView.hideTools();
},
emitSave() {
if (this.highlighted) {
this.updateWaypoints.flush();
document.removeEventListener('mouseup', this.emitSave);
this.listeningToMouseup = false;
}
},
},
created() {
this.updateWaypoints = debounce(this.updateWaypoints, 100);
this.emitSave.bind(this);
},
async mounted() {
await this.$nextTick();
/* Use nextTick to ensure this code runs after the component it is mixed into mounts.
* This will ensure this.shape is defined. */
this.sourceShape = this.findSourceShape();
this.setSource(this.sourceShape);
this.$once('click', () => {
this.$nextTick(() => {
if (store.getters.isReadOnly) {
return;
}
this.setupLinkTools();
});
});
const targetRef = this.getTargetRef
? this.getTargetRef()
: this.node.definition.get('targetRef');
// if flow doesn't have a targetRef such as incomplete node, return
if (!targetRef) return;
if (targetRef.id) {
const targetShape = this.graph.getElements().find(element => {
return element.component && element.component.node.definition === targetRef;
});
this.target = targetShape;
const sequenceFlowWaypoints = this.node.diagram.waypoint;
const sourceAnchorPoint = this.node.diagram.waypoint[0];
const targetAnchorPoint = sequenceFlowWaypoints[sequenceFlowWaypoints.length - 1];
const { x: targetX, y: targetY } = targetShape.position();
const targetAnchorOffset = {
x: targetAnchorPoint.x - targetX,
y: targetAnchorPoint.y - targetY,
};
const { x: sourceX, y: sourceY } = this.sourceShape.position();
const sourceAnchorOffset = {
x: sourceAnchorPoint.x - sourceX,
y: sourceAnchorPoint.y - sourceY,
};
if (sequenceFlowWaypoints) {
const sequenceVertices = sequenceFlowWaypoints
.slice(1, sequenceFlowWaypoints.length - 1)
.map(({ x, y }) => ({ x, y }));
this.shape.vertices(sequenceVertices);
}
this.setSource(this.sourceShape, sourceAnchorOffset);
this.setTarget(targetShape, targetAnchorOffset);
this.completeLink();
} else {
this.setTarget(targetRef);
this.paper.setInteractivity(false);
this.paper.el.addEventListener('mousemove', this.updateLinkTarget);
this.$emit('set-cursor', 'not-allowed');
if (this.isValidConnection) {
this.shape.stopListening(this.paper, 'blank:pointerdown link:pointerdown element:pointerdown', this.removeLink);
} else {
this.shape.listenToOnce(this.paper, 'blank:pointerdown link:pointerdown element:pointerdown', this.removeLink);
}
}
this.updateRouter();
this.shape.on('change:vertices', function () {
this.component.$emit('shape-resize');
});
if (store.getters.isReadOnly) {
this.$nextTick(() => {
this.paperManager.awaitScheduledUpdates().then(() => {
this.setShapeHighlight();
});
});
}
},
beforeDestroy() {
document.removeEventListener('mouseup', this.emitSave);
},
destroyed() {
this.updateWaypoints.cancel();
},
};