forked from cytoscape/cytoscape.js-edgehandles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cytoscape-edgehandles.js
1342 lines (1051 loc) · 44.1 KB
/
cytoscape-edgehandles.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
Copyright (c) The Cytoscape Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
;( function( $$, $ ) {
'use strict';
var debounce = (function(){
/**
* lodash 3.1.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeNow = Date.now;
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the debounced function return the result of the last
* `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it's invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = !!options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
if (id) {
clearTimeout(id);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
}
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
complete(trailingCall, maxTimeoutId);
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
complete(trailing, timeoutId);
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
return debounce;
})();
// ported lodash throttle function
var throttle = function( func, wait, options ){
var leading = true,
trailing = true;
if( options === false ){
leading = false;
} else if( typeof options === typeof {} ){
leading = 'leading' in options ? options.leading : leading;
trailing = 'trailing' in options ? options.trailing : trailing;
}
options = options || {};
options.leading = leading;
options.maxWait = wait;
options.trailing = trailing;
return debounce( func, wait, options );
};
// registers the extension on a cytoscape lib ref
var register = function( $$, $ ) {
if( !$$ ) {
return;
} // can't register if cytoscape unspecified
var defaults = {
preview: true, // whether to show added edges preview before releasing selection
stackOrder: 4, // Controls stack order of edgehandles canvas element by setting it's z-index
handleSize: 10, // the size of the edge handle put on nodes
handleIcon: false,
handleColor: '#ff0000', // the colour of the handle and the line drawn from it
handleLineType: 'ghost', // can be 'ghost' for real edge, 'straight' for a straight line, or 'draw' for a draw-as-you-go line
handleLineWidth: 1, // width of handle line in pixels
handleNodes: 'node', // selector/filter function for whether edges can be made from a given node
hoverDelay: 150, // time spend over a target node before it is considered a target selection
cxt: false, // whether cxt events trigger edgehandles (useful on touch)
enabled: true, // whether to start the plugin in the enabled state
toggleOffOnLeave: false, // whether an edge is cancelled by leaving a node (true), or whether you need to go over again to cancel (false; allows multiple edges in one pass)
edgeType: function( sourceNode, targetNode ) {
// can return 'flat' for flat edges between nodes or 'node' for intermediate node between them
// returning null/undefined means an edge can't be added between the two nodes
return 'flat';
},
loopAllowed: function( node ) {
// for the specified node, return whether edges from itself to itself are allowed
return false;
},
nodeLoopOffset: -50, // offset for edgeType: 'node' loops
nodeParams: function( sourceNode, targetNode ) {
// for edges between the specified source and target
// return element object to be passed to cy.add() for intermediary node
return {};
},
edgeParams: function( sourceNode, targetNode, i ) {
// for edges between the specified source and target
// return element object to be passed to cy.add() for edge
// NB: i indicates edge index in case of edgeType: 'node'
return {};
},
start: function( sourceNode ) {
// fired when edgehandles interaction starts (drag on handle)
},
complete: function( sourceNode, targetNodes, addedEntities ) {
// fired when edgehandles is done and entities are added
},
stop: function( sourceNode ) {
// fired when edgehandles interaction is stopped (either complete with added edges or incomplete)
}
};
var edgehandles = function( params ) {
var cy = this;
var fn = params;
var container = cy.container();
var functions = {
destroy: function() {
var $container = $( this );
var data = $container.data( 'cyedgehandles' );
if( data == null ) {
return;
}
data.unbind();
$container.data( 'cyedgehandles', {} );
return $container;
},
option: function( name, value ) {
var $container = $( this );
var data = $container.data( 'cyedgehandles' );
if( data == null ) {
return;
}
var options = data.options;
if( value === undefined ) {
if( typeof name == typeof {} ) {
var newOpts = name;
options = $.extend( true, {}, defaults, newOpts );
data.options = options;
} else {
return options[ name ];
}
} else {
options[ name ] = value;
}
$container.data( 'cyedgehandles', data );
return $container;
},
disable: function() {
return functions.option.apply( this, [ 'enabled', false ] );
},
enable: function() {
return functions.option.apply( this, [ 'enabled', true ] );
},
resize: function() {
var $container = $( this );
$container.trigger( 'cyedgehandles.resize' );
},
drawon: function() {
$( this ).trigger( 'cyedgehandles.drawon' );
},
drawoff: function() {
$( this ).trigger( 'cyedgehandles.drawoff' );
},
init: function() {
var self = this;
var opts = $.extend( true, {}, defaults, params );
var $container = $( this );
var $canvas = $( '<canvas></canvas>' );
var handle;
var line, linePoints;
var mdownOnHandle = false;
var grabbingNode = false;
var inForceStart = false;
var hx, hy, hr;
var hoverTimeout;
var drawsClear = true;
var ghostNode;
var ghostEdge;
var sourceNode;
var drawMode = false;
cy.on( 'resize', function() {
$container.trigger( 'cyedgehandles.resize' );
});
$container.append( $canvas );
var _sizeCanvas = debounce( function(){
$canvas
.attr( 'height', $container.height() )
.attr( 'width', $container.width() )
.css( {
'position': 'absolute',
'top': 0,
'left': 0,
'z-index': opts.stackOrder
} )
;
setTimeout(function(){
var canvasBb = $canvas.offset();
var containerBb = $container.offset();
$canvas
.css( {
'top': -( canvasBb.top - containerBb.top ),
'left': -( canvasBb.left - containerBb.left )
} )
;
}, 0);
}, 250 );
var sizeCanvas = function(){
clearDraws();
_sizeCanvas();
};
sizeCanvas();
var winResizeHandler;
$( window ).bind( 'resize', winResizeHandler = function() {
sizeCanvas();
} );
var ctrResizeHandler;
$container.bind( 'cyedgehandles.resize', ctrResizeHandler = function() {
sizeCanvas();
} );
var prevUngrabifyState;
var ctrDrawonHandler;
$container.on( 'cyedgehandles.drawon', ctrDrawonHandler = function() {
drawMode = true;
prevUngrabifyState = cy.autoungrabify();
cy.autoungrabify( true );
} );
var ctrDrawoffHandler;
$container.on( 'cyedgehandles.drawoff', ctrDrawoffHandler = function() {
drawMode = false;
cy.autoungrabify( prevUngrabifyState );
} );
var ctx = $canvas[ 0 ].getContext( '2d' );
// write options to data
var data = $container.data( 'cyedgehandles' );
if( data == null ) {
data = {};
}
data.options = opts;
var optCache;
function options() {
return optCache || ( optCache = $container.data( 'cyedgehandles' ).options );
}
function enabled() {
return options().enabled;
}
function disabled() {
return !enabled();
}
function clearDraws() {
if( drawsClear ) {
return;
} // break early to be efficient
var w = $container.width();
var h = $container.height();
ctx.clearRect( 0, 0, w, h );
drawsClear = true;
}
var lastPanningEnabled, lastZoomingEnabled, lastBoxSelectionEnabled;
function disableGestures() {
lastPanningEnabled = cy.panningEnabled();
lastZoomingEnabled = cy.zoomingEnabled();
lastBoxSelectionEnabled = cy.boxSelectionEnabled();
cy
.zoomingEnabled( false )
.panningEnabled( false )
.boxSelectionEnabled( false );
}
function resetGestures() {
cy
.zoomingEnabled( lastZoomingEnabled )
.panningEnabled( lastPanningEnabled )
.boxSelectionEnabled( lastBoxSelectionEnabled );
}
function resetToDefaultState() {
clearDraws();
//setTimeout(function(){
cy.nodes()
.removeClass( 'edgehandles-hover' )
.removeClass( 'edgehandles-source' )
.removeClass( 'edgehandles-target' );
cy.$( '.edgehandles-ghost' ).remove();
//}, 1);
linePoints = null;
sourceNode = null;
resetGestures();
}
function makePreview( source, target ) {
makeEdges( true );
target.trigger( 'cyedgehandles.addpreview' );
}
function removePreview( source, target ) {
source.edgesWith( target ).filter( '.edgehandles-preview' ).remove();
target
.neighborhood( 'node.edgehandles-preview' )
.closedNeighborhood( '.edgehandles-preview' )
.remove();
target.trigger( 'cyedgehandles.removepreview' );
}
function drawHandle( hx, hy, hr ) {
ctx.fillStyle = options().handleColor;
ctx.strokeStyle = options().handleColor;
ctx.beginPath();
ctx.arc( hx, hy, hr, 0, 2 * Math.PI );
ctx.closePath();
ctx.fill();
if(options().handleIcon){
var icon = options().handleIcon;
var width = icon.width*cy.zoom(), height = icon.height*cy.zoom();
ctx.drawImage(icon, hx-(width/2), hy-(height/2), width, height);
}
drawsClear = false;
}
var lineDrawRate = 1000 / 60;
var drawLine = throttle( function( hx, hy, x, y ) {
if( options().handleLineType !== 'ghost' ) {
ctx.fillStyle = options().handleColor;
ctx.strokeStyle = options().handleColor;
ctx.lineWidth = options().handleLineWidth;
}
// draw line based on type
switch( options().handleLineType ) {
case 'ghost':
if( !ghostNode || ghostNode.removed() ) {
drawHandle();
ghostNode = cy.add( {
group: 'nodes',
classes: 'edgehandles-ghost edgehandles-ghost-node',
css: {
'background-color': 'blue',
'width': 0.0001,
'height': 0.0001,
'opacity': 0,
'events': 'no'
},
position: {
x: 0,
y: 0
}
} );
ghostEdge = cy.add( {
group: 'edges',
classes: 'edgehandles-ghost edgehandles-ghost-edge',
data: {
source: sourceNode.id(),
target: ghostNode.id()
},
css: {
'events': 'no'
}
} );
}
ghostNode.renderedPosition( {
x: x,
y: y
} );
break;
case 'straight':
ctx.beginPath();
ctx.moveTo( hx, hy );
ctx.lineTo( x, y );
ctx.closePath();
ctx.stroke();
break;
case 'draw':
default:
if( linePoints == null ) {
linePoints = [ [ x, y ] ];
} else {
linePoints.push( [ x, y ] );
}
ctx.beginPath();
ctx.moveTo( hx, hy );
for( var i = 0; i < linePoints.length; i++ ) {
var pt = linePoints[ i ];
ctx.lineTo( pt[ 0 ], pt[ 1 ] );
}
ctx.stroke();
break;
}
if( options().handleLineType !== 'ghost' ) {
drawsClear = false;
}
}, lineDrawRate, { leading: true } );
function makeEdges( preview, src, tgt ) {
// console.log('make edges', preview);
var source = src ? src : cy.nodes( '.edgehandles-source' );
var targets = tgt ? tgt : cy.nodes( '.edgehandles-target' );
var classes = preview ? 'edgehandles-preview' : '';
var added = cy.collection();
if( !src && !tgt && !preview && options().preview ) {
cy.$( '.edgehandles-ghost' ).remove();
}
if( source.size() === 0 || targets.size() === 0 ) {
return; // nothing to do :(
}
// just remove preview class if we already have the edges
if( !src && !tgt ) {
if( !preview && options().preview ) {
added = cy.elements( '.edgehandles-preview' ).removeClass( 'edgehandles-preview' );
options().complete( source, targets, added );
source.trigger( 'cyedgehandles.complete' );
return;
} else {
// remove old previews
cy.elements( '.edgehandles-preview' ).remove();
}
}
for( var i = 0; i < targets.length; i++ ) {
var target = targets[ i ];
switch( options().edgeType( source, target ) ) {
case 'node':
var p1 = source.position();
var p2 = target.position();
var p;
if( source.id() === target.id() ) {
p = {
x: p1.x + options().nodeLoopOffset,
y: p1.y + options().nodeLoopOffset
};
} else {
p = {
x: ( p1.x + p2.x ) / 2,
y: ( p1.y + p2.y ) / 2
};
}
var interNode = cy.add( $.extend( true, {
group: 'nodes',
position: p
}, options().nodeParams( source, target ) ) ).addClass( classes );
var source2inter = cy.add( $.extend( true, {
group: 'edges',
data: {
source: source.id(),
target: interNode.id()
}
}, options().edgeParams( source, target, 0 ) ) ).addClass( classes );
var inter2target = cy.add( $.extend( true, {
group: 'edges',
data: {
source: interNode.id(),
target: target.id()
}
}, options().edgeParams( source, target, 1 ) ) ).addClass( classes );
added = added.add( interNode ).add( source2inter ).add( inter2target );
break;
case 'flat':
var edge = cy.add( $.extend( true, {
group: 'edges',
data: {
source: source.id(),
target: target.id()
}
}, options().edgeParams( source, target, 0 ) ) ).addClass( classes );
added = added.add( edge );
break;
default:
target.removeClass( 'edgehandles-target' );
break; // don't add anything
}
}
if( !preview ) {
options().complete( source, targets, added );
source.trigger( 'cyedgehandles.complete' );
}
}
function hoverOver( node ) {
var target = node;
clearTimeout( hoverTimeout );
hoverTimeout = setTimeout( function() {
var source = cy.nodes( '.edgehandles-source' );
var isLoop = node.hasClass( 'edgehandles-source' );
var loopAllowed = options().loopAllowed( node );
var isGhost = node.hasClass( 'edgehandles-ghost-node' );
var noEdge = options().edgeType( source, node ) == null;
if( isGhost || noEdge ) {
return;
}
if( !isLoop || ( isLoop && loopAllowed ) ) {
node.addClass( 'edgehandles-hover' );
node.toggleClass( 'edgehandles-target' );
if( options().preview ) {
if( node.hasClass( 'edgehandles-target' ) ) {
makePreview( source, target );
} else {
removePreview( source, target );
}
}
}
}, options().hoverDelay );
}
function hoverOut( node ) {
var target = node;
node.removeClass( 'edgehandles-hover' );
clearTimeout( hoverTimeout );
if( options().toggleOffOnLeave ) {
var source = sourceNode;
node.removeClass( 'edgehandles-target' );
removePreview( source, target );
}
}
cy.ready( function( e ) {
lastPanningEnabled = cy.panningEnabled();
lastZoomingEnabled = cy.zoomingEnabled();
lastBoxSelectionEnabled = cy.boxSelectionEnabled();
// console.log('handles on ready')
var lastActiveId;
var transformHandler;
cy.bind( 'zoom pan', transformHandler = function() {
clearDraws();
} );
var lastMdownHandler;
var startHandler, hoverHandler, leaveHandler, grabNodeHandler, freeNodeHandler, dragNodeHandler, forceStartHandler, removeHandler, cxtstartHandler, tapToStartHandler, cxtdragHandler, cxtdragoverHandler, cxtdragoutHandler, cxtendHandler, dragHandler, grabHandler;
cy.on( 'mouseover tap', 'node', startHandler = function( e ) {
var node = this;
if( disabled() || drawMode || mdownOnHandle || grabbingNode || this.hasClass( 'edgehandles-preview' ) || inForceStart || this.hasClass( 'edgehandles-ghost-node' ) || node.filter( options().handleNodes ).length === 0 ) {
return; // don't override existing handle that's being dragged
// also don't trigger when grabbing a node etc
}
//console.log('mouseover startHandler %s %o', this.id(), this);
if( lastMdownHandler ) {
$container[ 0 ].removeEventListener( 'mousedown', lastMdownHandler, true );
$container[ 0 ].removeEventListener( 'touchstart', lastMdownHandler, true );
}
var source = this;
var p = node.renderedPosition();
var h = node.renderedOuterHeight();
lastActiveId = node.id();
// remove old handle
clearDraws();
hr = options().handleSize / 2 * cy.zoom();
hx = p.x;
hy = p.y - h / 2;
// add new handle
drawHandle( hx, hy, hr );
node.trigger( 'cyedgehandles.showhandle' );
function mdownHandler( e ) {
$container[ 0 ].removeEventListener( 'mousedown', mdownHandler, true );
$container[ 0 ].removeEventListener( 'touchstart', mdownHandler, true );
var pageX = !e.touches ? e.pageX : e.touches[ 0 ].pageX;
var pageY = !e.touches ? e.pageY : e.touches[ 0 ].pageY;
var x = pageX - $container.offset().left;
var y = pageY - $container.offset().top;
var hrTarget = hr;
if( e.button !== 0 && !e.touches ) {
return; // sorry, no right clicks allowed
}
if( Math.abs( x - hx ) > hrTarget || Math.abs( y - hy ) > hrTarget ) {
return; // only consider this a proper mousedown if on the handle
}
if( inForceStart ) {
return; // we don't want this going off if we have the forced start to consider
}
// console.log('mdownHandler %s %o', node.id(), node);
mdownOnHandle = true;
e.preventDefault();
e.stopPropagation();
sourceNode = node;
node.addClass( 'edgehandles-source' );
node.trigger( 'cyedgehandles.start' );
function doneMoving( dmEvent ) {
// console.log('doneMoving %s %o', node.id(), node);
if( !mdownOnHandle || inForceStart ) {
return;
}
var $this = $( this );
mdownOnHandle = false;
$( window ).unbind( 'mousemove touchmove', moveHandler );
makeEdges();
resetToDefaultState();
options().stop( node );
node.trigger( 'cyedgehandles.stop' );
}
$( window ).one( 'mouseup touchend touchcancel blur', doneMoving ).bind( 'mousemove touchmove', moveHandler );
disableGestures();
options().start( node );
return false;
}
function moveHandler( e ) {
// console.log('mousemove moveHandler %s %o', node.id(), node);
var pageX = !e.originalEvent.touches ? e.pageX : e.originalEvent.touches[ 0 ].pageX;
var pageY = !e.originalEvent.touches ? e.pageY : e.originalEvent.touches[ 0 ].pageY;
var x = pageX - $container.offset().left;
var y = pageY - $container.offset().top;
if( options().handleLineType !== 'ghost' ) {
clearDraws();
drawHandle( hx, hy, hr );
}
drawLine( hx, hy, x, y );
return false;
}
$container[ 0 ].addEventListener( 'mousedown', mdownHandler, true );
$container[ 0 ].addEventListener( 'touchstart', mdownHandler, true );
lastMdownHandler = mdownHandler;
} ).on( 'mouseover tapdragover', 'node', hoverHandler = function() {
var node = this;
var target = this;
// console.log('mouseover hoverHandler')
if( disabled() || drawMode || this.hasClass( 'edgehandles-preview' ) ) {
return; // ignore preview nodes
}
if( mdownOnHandle ) { // only handle mdown case
// console.log( 'mouseover hoverHandler %s $o', node.id(), node );
hoverOver( node );
return false;
}
} ).on( 'mouseout tapdragout', 'node', leaveHandler = function() {
var node = this;
if( drawMode ) {
return;
}
if( mdownOnHandle ) {
hoverOut( node );
}