forked from jgraph/mxgraph
-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathConnectionHandler.ts
More file actions
2131 lines (1859 loc) · 66 KB
/
Copy pathConnectionHandler.ts
File metadata and controls
2131 lines (1859 loc) · 66 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
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 2021-present The maxGraph project Contributors
Copyright (c) 2006-2016, JGraph Ltd
Copyright (c) 2006-2016, Gaudenz Alder
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Geometry from '../geometry/Geometry.js';
import Cell from '../cell/Cell.js';
import Point from '../geometry/Point.js';
import EventObject from '../event/EventObject.js';
import InternalEvent from '../event/InternalEvent.js';
import {
DEFAULT_HOTSPOT,
DEFAULT_INVALID_COLOR,
HIGHLIGHT_STROKEWIDTH,
INVALID_COLOR,
NONE,
OUTLINE_HIGHLIGHT_COLOR,
OUTLINE_HIGHLIGHT_STROKEWIDTH,
TOOLTIP_VERTICAL_OFFSET,
VALID_COLOR,
} from '../../util/Constants.js';
import { getRotatedPoint, toRadians } from '../../util/mathUtils.js';
import { convertPoint, getOffset } from '../../util/styleUtils.js';
import InternalMouseEvent from '../event/InternalMouseEvent.js';
import ImageShape from '../shape/node/ImageShape.js';
import CellMarker from '../cell/CellMarker.js';
import ConstraintHandler from '../handler/ConstraintHandler.js';
import PolylineShape from '../shape/edge/PolylineShape.js';
import EventSource from '../event/EventSource.js';
import Rectangle from '../geometry/Rectangle.js';
import {
getClientX,
getClientY,
isAltDown,
isConsumed,
isShiftDown,
} from '../../util/EventUtils.js';
import Image from '../image/ImageBox.js';
import CellState from '../cell/CellState.js';
import type { AbstractGraph } from '../AbstractGraph.js';
import ConnectionConstraint from '../other/ConnectionConstraint.js';
import Shape from '../shape/Shape.js';
import type {
CellStyle,
ColorValue,
GraphPlugin,
Listenable,
MouseListenerSet,
} from '../../types.js';
import { log } from '../../internal/utils.js';
type FactoryMethod = (
source: Cell | null,
target: Cell | null,
style?: CellStyle
) => Cell;
/**
* Graph event handler that creates new connections.
* Uses {@link CellMarker} for finding and highlighting the source and target vertices and {@link factoryMethod} to create the edge instance.
*
* This handler is enabled using {@link AbstractGraph.setConnectable}.
*
* Example:
*
* ```javascript
* new ConnectionHandler(graph, (source, target, style)=>
* {
* edge = new Cell('', new Geometry());
* edge.setEdge(true);
* edge.setStyle(style);
* edge.geometry.relative = true;
* return edge;
* });
* ```
*
* Here is an alternative solution that just sets a specific user object for new edges by overriding {@link insertEdge}.
*
* ```javascript
* originalConnectionHandlerInsertEdge = connectionHandler.insertEdge;
* connectionHandler.insertEdge = (parent, id, value, source, target, style) => {
* value = 'Test';
* return originalConnectionHandlerInsertEdge.apply(this, arguments);
* };
* ```
*
* ### Using images to trigger connections
*
* This handler uses {@link CellMarker} to find the source and target cell for
* the new connection and creates a new edge using {@link connect}. The new edge is
* created using {@link createEdge} which in turn uses {@link factoryMethod} or creates a
* new default edge.
*
* The handler uses a "highlight-paradigm" for indicating if a cell is being
* used as a source or target terminal, as seen in other diagramming products.
* In order to allow both, moving and connecting cells at the same time,
* {@link DEFAULT_HOTSPOT} is used in the handler to determine the hotspot
* of a cell, that is, the region of the cell which is used to trigger a new
* connection. The constant is a value between 0 and 1 that specifies the
* amount of the width and height around the center to be used for the hotspot
* of a cell and its default value is 0.5. In addition,
* {@link MIN_HOTSPOT_SIZE} defines the minimum number of pixels for the
* width and height of the hotspot.
*
* This solution, while standards compliant, may be somewhat confusing because
* there is no visual indicator for the hotspot and the highlight is seen to
* switch on and off while the mouse is being moved in and out. Furthermore,
* this paradigm does not allow to create different connections depending on
* the highlighted hotspot as there is only one hotspot per cell, and it
* normally does not allow cells to be moved and connected at the same time as
* there is no clear indication of the connectable area of the cell.
*
* To come across these issues, the handle has an additional {@link createIcons} hook
* with a default implementation that allows to create one icon to be used to
* trigger new connections. If this icon is specified, then new connections can
* only be created if the image is clicked while the cell is being highlighted.
* The {@link createIcons} hook may be overridden to create more than one
* {@link ImageShape} for creating new connections, but the default implementation
* supports one image and is used as follows:
*
* In order to display the "connect image" whenever the mouse is over the cell, an DEFAULT_HOTSPOT of 1 should be used:
*
* ```javascript
* mxConstants.DEFAULT_HOTSPOT = 1;
* ```
*
* In order to avoid confusion with the highlighting, the highlight color should not be used with a connect image:
*
* ```javascript
* mxConstants.HIGHLIGHT_COLOR = null;
* ```
*
* To install the image, the connectImage field of the ConnectionHandler must be assigned a new {@link Image} instance:
*
* ```javascript
* connectImage = new ImageBox('images/green-dot.gif', 14, 14);
* ```
*
* This will use the green-dot.gif with a width and height of 14 pixels as the
* image to trigger new connections. In createIcons the icon field of the
* handler will be set in order to remember the icon that has been clicked for
* creating the new connection. This field will be available under selectedIcon
* in the connect method, which may be overridden to take the icon that
* triggered the new connection into account. This is useful if more than one
* icon may be used to create a connection.
*
* ### Events
*
* #### InternalEvent.START
*
* Fires when a new connection is being created by the user. The `state`
* property contains the state of the source cell.
*
* #### InternalEvent.CONNECT
*
* Fires between begin- and endUpdate in {@link connect}. The `cell`
* property contains the inserted edge, the `event` and `target`
* properties contain the respective arguments that were passed to {@link connect} (where
* target corresponds to the dropTarget argument). Finally, the `terminal`
* property corresponds to the target argument in {@link connect} or the clone of the source
* terminal if {@link createTarget} is enabled.
*
* Note that the target is the cell under the mouse where the mouse button was released.
* Depending on the logic in the handler, this doesn't necessarily have to be the target
* of the inserted edge. To print the source, target or any optional ports IDs that the
* edge is connected to, the following code can be used. To get more details about the
* actual connection point, {@link AbstractGraph.getConnectionConstraint} can be used. To resolve
* the port IDs, use {@link GraphDataModel.getCell}.
*
* ```javascript
* graph.getPlugin('ConnectionHandler')?.addListener(mxEvent.CONNECT, (sender, evt) => {
* const edge = evt.getProperty('cell');
* const source = graph.getDataModel().getTerminal(edge, true);
* const target = graph.getDataModel().getTerminal(edge, false);
*
* const style = graph.getCellStyle(edge);
* const sourcePortId = style.sourcePort;
* const targetPortId = style.targetPort;
*
* GlobalConfig.logger.show();
* GlobalConfig.logger.debug(`connect edge=${edge.id} source=${source.id} target=${target.id} sourcePort=${sourcePortId} targetPort=${targetPortId}`);
* });
* ```
*
* #### InternalEvent.RESET
*
* Fires when the {@link reset} method is invoked.
*
* @category Plugin
*/
export default class ConnectionHandler
extends EventSource
implements GraphPlugin, MouseListenerSet
{
static readonly pluginId = 'ConnectionHandler';
previous: CellState | null = null;
iconState: CellState | null = null;
icons: ImageShape[] = [];
cell: Cell | null = null;
currentPoint: Point | null = null;
sourceConstraint: ConnectionConstraint | null = null;
shape: Shape | null = null;
icon: ImageShape | null = null;
originalPoint: Point | null = null;
currentState: CellState | null = null;
selectedIcon: ImageShape | null = null;
waypoints: Point[] = [];
/**
* Reference to the enclosing {@link AbstractGraph}.
*/
graph: AbstractGraph;
/**
* Function that is used for creating new edges. The function takes the
* source and target {@link Cell} as the first and second argument and returns
* a new {@link Cell} that represents the edge. This is used in {@link createEdge}.
*/
factoryMethod: FactoryMethod | null = null;
/**
* Specifies if icons should be displayed inside the graph container instead
* of the overlay pane. This is used for HTML labels on vertices which hide
* the connect icon. This has precedence over {@link moveIconBack} when set
* to true.
* @default `false`
*/
moveIconFront = false;
/**
* Specifies if icons should be moved to the back of the overlay pane. This can
* be set to true if the icons of the connection handler conflict with other
* handles, such as the vertex label move handle.
* @default false
*/
moveIconBack = false;
/**
* {@link Image} that is used to trigger the creation of a new connection.
* This is used in {@link createIcons}.
* @default null
*/
connectImage: Image | null = null;
/**
* Specifies if the connect icon should be centered on the target state while connections are being previewed.
* @default false
*/
targetConnectImage = false;
/**
* Specifies if events are handled.
* @default false
*/
enabled = false;
/**
* Specifies if new edges should be selected.
* @default true
*/
select = true;
/**
* Specifies if {@link createTargetVertex} should be called if no target was under the
* mouse for the new connection. Setting this to true means the connection
* will be drawn as valid if no target is under the mouse, and
* {@link createTargetVertex} will be called before the connection is created between
* the source cell and the newly created vertex in {@link createTargetVertex}, which
* can be overridden to create a new target.
* @default false
*/
createTarget = false;
/**
* Holds the {@link CellMarker} used for finding source and target cells.
*/
marker: CellMarker;
/**
* Holds the {@link ConstraintHandler} used for drawing and highlighting constraints.
*/
constraintHandler: ConstraintHandler;
/**
* Holds the current validation error while connections are being created.
* @default null
*/
error: string | null = null;
/**
* Specifies if single clicks should add waypoints on the new edge.
* @default false
*/
waypointsEnabled = false;
/**
* Specifies if the connection handler should ignore the state of the mouse button when highlighting the source.
*
* When false, that is, the handler only highlights the source if no button is being pressed.
*
* @default false
*/
ignoreMouseDown = false;
/**
* Holds the {@link Point} where the mouseDown took place while the handler is active.
*/
first: Point | null = null;
/**
* Holds the offset for connect icons during connection preview.
* Default is mxPoint(0, {@link TOOLTIP_VERTICAL_OFFSET}).
* Note that placing the icon under the mouse pointer with an
* offset of (0,0) will affect hit detection.
*/
connectIconOffset = new Point(0, TOOLTIP_VERTICAL_OFFSET);
/**
* Optional {@link CellState} that represents the preview edge while the
* handler is active. This is created in {@link createEdgeState}.
*/
edgeState: CellState | null = null;
/**
* Holds the change event listener for later removal.
*/
changeHandler: (sender: Listenable) => void;
/**
* Holds the drill event listener for later removal.
*/
drillHandler: (sender: Listenable) => void;
/**
* Counts the number of mouseDown events since the start. The initial mouse
* down event counts as 1.
*/
mouseDownCounter = 0;
/**
* Switch to enable moving the preview away from the mouse pointer. This is required in browsers
* where the preview cannot be made transparent to events and if the built-in hit detection on
* the HTML elements in the page should be used.
* @default false
*/
movePreviewAway = false;
/**
* Specifies if connections to the outline of a highlighted target should be
* enabled. This will allow to place the connection point along the outline of
* the highlighted target.
* @default false
*/
outlineConnect = false;
/**
* Specifies if the actual shape of the edge state should be used for the preview.
* This is ignored if no edge state is created in {@link createEdgeState}.
* @default false
*/
livePreview = false;
/**
* Specifies the cursor to be used while the handler is active.
* @default null
*/
cursor: string | null = null;
/**
* Defines the cursor for a connectable state.
* @default 'pointer'
* @since 0.20.0
*/
cursorConnect: string = 'pointer';
/**
* Specifies if new edges should be inserted before the source vertex in the
* cell hierarchy. Default is false for backwards compatibility.
*/
insertBeforeSource = false;
escapeHandler: () => void;
/**
* Constructs an event handler that connects vertices using the specified
* factory method to create the new edges.
*
* @param graph Reference to the enclosing {@link AbstractGraph}.
* @param factoryMethod Optional function to create the edge. The function takes
* the source and target {@link Cell} as the first and second argument and an
* optional cell style from the preview as the third argument. It returns
* the {@link Cell} that represents the new edge.
*/
constructor(graph: AbstractGraph, factoryMethod: FactoryMethod | null = null) {
super();
this.graph = graph;
this.factoryMethod = factoryMethod;
this.graph.addMouseListener(this);
this.marker = this.createMarker();
this.constraintHandler = this.createConstraintHandler();
// Redraws the icons if the graph changes
this.changeHandler = (sender: Listenable) => {
if (this.iconState) {
this.iconState = this.graph.getView().getState(this.iconState.cell);
}
if (this.iconState) {
this.redrawIcons(this.icons, this.iconState);
this.constraintHandler.reset();
} else if (this.previous && !this.graph.view.getState(this.previous.cell)) {
this.reset();
}
};
this.graph.getDataModel().addListener(InternalEvent.CHANGE, this.changeHandler);
this.graph.getView().addListener(InternalEvent.SCALE, this.changeHandler);
this.graph.getView().addListener(InternalEvent.TRANSLATE, this.changeHandler);
this.graph
.getView()
.addListener(InternalEvent.SCALE_AND_TRANSLATE, this.changeHandler);
// Removes the icon if we step into/up or start editing
this.drillHandler = (sender: Listenable) => {
this.reset();
};
this.graph.addListener(InternalEvent.START_EDITING, this.drillHandler);
this.graph.getView().addListener(InternalEvent.DOWN, this.drillHandler);
this.graph.getView().addListener(InternalEvent.UP, this.drillHandler);
// Handles escape keystrokes
this.escapeHandler = () => {
this.reset();
};
this.graph.addListener(InternalEvent.ESCAPE, this.escapeHandler);
}
/**
* Hook for subclasses to change the implementation of {@link ConstraintHandler} used here.
* @since 0.21.0
*/
protected createConstraintHandler() {
return new ConstraintHandler(this.graph);
}
/**
* Returns true if events are handled. This implementation
* returns <enabled>.
*/
isEnabled() {
return this.enabled;
}
/**
* Enables or disables event handling. This implementation
* updates <enabled>.
*
* @param enabled Boolean that specifies the new enabled state.
*/
setEnabled(enabled: boolean) {
this.enabled = enabled;
}
/**
* Returns <insertBeforeSource> for non-loops and false for loops.
*
* @param edge {@link Cell} that represents the edge to be inserted.
* @param source {@link Cell} that represents the source terminal.
* @param target {@link Cell} that represents the target terminal.
* @param evt Mousedown event of the connect gesture.
* @param dropTarget {@link Cell} that represents the cell under the mouse when it was
* released.
*/
isInsertBefore(
edge: Cell,
source: Cell | null,
target: Cell | null,
evt: MouseEvent,
dropTarget: Cell | null
) {
return this.insertBeforeSource && source !== target;
}
/**
* Returns <createTarget>.
*
* @param evt Current active native pointer event.
*/
isCreateTarget(evt: Event) {
return this.createTarget;
}
/**
* Sets <createTarget>.
*/
setCreateTarget(value: boolean) {
this.createTarget = value;
}
/**
* Creates the preview shape for new connections.
*/
createShape() {
// Creates the edge preview
const shape =
this.livePreview && this.edgeState
? this.graph.cellRenderer.createShape(this.edgeState)
: new PolylineShape([], INVALID_COLOR);
if (shape && shape.node) {
shape.dialect = 'svg';
shape.scale = this.graph.view.scale;
shape.pointerEvents = false;
shape.isDashed = true;
shape.init(this.graph.getView().getOverlayPane());
InternalEvent.redirectMouseEvents(shape.node, this.graph, null);
}
return shape;
}
/**
* Returns true if the given cell is connectable. This is a hook to
* disable floating connections. This implementation returns true.
*/
isConnectableCell(cell: Cell) {
return true;
}
/**
* Creates and returns the {@link CellMarker} used in {@link marker}.
*/
createMarker() {
return new ConnectionHandlerCellMarker(this.graph, this);
}
/**
* Starts a new connection for the given state and coordinates.
*/
start(state: CellState, x: number, y: number, edgeState?: CellState) {
this.previous = state;
this.first = new Point(x, y);
this.edgeState = edgeState ?? this.createEdgeState();
// Marks the source state
this.marker.currentColor = this.marker.validColor;
this.marker.markedState = state;
this.marker.mark();
this.fireEvent(new EventObject(InternalEvent.START, { state: this.previous }));
}
/**
* Returns true if the source terminal has been clicked and a new
* connection is currently being previewed.
*/
isConnecting() {
return !!this.first && !!this.shape;
}
/**
* Returns {@link AbstractGraph.isValidSource} for the given source terminal.
*
* @param cell {@link Cell} that represents the source terminal.
* @param me {@link MouseEvent} that is associated with this call.
*/
isValidSource(cell: Cell, me: InternalMouseEvent) {
return this.graph.isValidSource(cell);
}
/**
* Returns true. The call to {@link AbstractGraph.isValidTarget} is implicit by calling
* {@link AbstractGraph.getEdgeValidationError} in <validateConnection>. This is an
* additional hook for disabling certain targets in this specific handler.
*
* @param cell {@link Cell} that represents the target terminal.
*/
isValidTarget(cell: Cell) {
return true;
}
/**
* Returns the error message or an empty string if the connection for the
* given source target pair is not valid. Otherwise it returns null. This
* implementation uses {@link AbstractGraph.getEdgeValidationError}.
*
* @param source {@link Cell} that represents the source terminal.
* @param target {@link Cell} that represents the target terminal.
*/
validateConnection(source: Cell, target: Cell) {
if (!this.isValidTarget(target)) {
return '';
}
return this.graph.getEdgeValidationError(null, source, target);
}
/**
* Hook to return the {@link Image} used for the connection icon of the given
* {@link CellState}. This implementation returns {@link connectImage}.
*
* @param state {@link CellState} whose connect image should be returned.
*/
getConnectImage(state: CellState) {
return this.connectImage;
}
/**
* Returns true if the state has a HTML label in the graph's container, otherwise
* it returns {@link oveIconFront}.
*
* @param state <CellState> whose connect icons should be returned.
*/
isMoveIconToFrontForState(state: CellState) {
if (state.text && state.text.node.parentNode === this.graph.container) {
return true;
}
return this.moveIconFront;
}
/**
* Creates the array {@link ImageShape}s that represent the connect icons for
* the given {@link CellState}.
*
* @param state {@link CellState} whose connect icons should be returned.
*/
createIcons(state: CellState) {
const image = this.getConnectImage(state);
if (image) {
this.iconState = state;
const icons = [];
// Cannot use HTML for the connect icons because the icon receives all
// mouse move events in IE, must use VML and SVG instead even if the
// connect-icon appears behind the selection border and the selection
// border consumes the events before the icon gets a chance
const bounds = new Rectangle(0, 0, image.width, image.height);
const icon = new ImageShape(bounds, image.src, undefined, undefined, 0);
icon.preserveImageAspect = false;
if (this.isMoveIconToFrontForState(state)) {
icon.dialect = 'strictHtml';
icon.init(this.graph.container);
} else {
icon.dialect = 'svg';
icon.init(this.graph.getView().getOverlayPane());
// Move the icon back in the overlay pane
if (this.moveIconBack && icon.node.parentNode && icon.node.previousSibling) {
icon.node.parentNode.insertBefore(icon.node, icon.node.parentNode.firstChild);
}
}
icon.node.style.cursor = this.cursorConnect;
// Events transparency
const getState = () => {
return this.currentState ?? state;
};
// Updates the local icon before firing the mouse down event.
const mouseDown = (evt: MouseEvent) => {
if (!isConsumed(evt)) {
this.icon = icon;
this.graph.fireMouseEvent(
InternalEvent.MOUSE_DOWN,
new InternalMouseEvent(evt, getState())
);
}
};
InternalEvent.redirectMouseEvents(icon.node, this.graph, getState, mouseDown);
icons.push(icon);
this.redrawIcons(icons, this.iconState);
return icons;
}
return [];
}
/**
* Redraws the given array of {@link ImageShape}s.
*
* @param icons Array of {@link ImageShape}s to be redrawn.
* @param state {@link CellState} under the mouse.
*/
redrawIcons(icons: ImageShape[], state: CellState) {
if (icons[0] && icons[0].bounds) {
const pos = this.getIconPosition(icons[0], state);
icons[0].bounds.x = pos.x;
icons[0].bounds.y = pos.y;
icons[0].redraw();
}
}
/**
* Returns the center position of the given icon.
*
* @param icon The connect icon of {@link ImageShape} with the mouse.
* @param state {@link CellState} under the mouse.
*/
getIconPosition(icon: ImageShape, state: CellState) {
const { scale } = this.graph.getView();
let cx = state.getCenterX();
let cy = state.getCenterY();
if (this.graph.isSwimlane(state.cell)) {
const size = this.graph.getStartSize(state.cell);
cx = size.width !== 0 ? state.x + (size.width * scale) / 2 : cx;
cy = size.height !== 0 ? state.y + (size.height * scale) / 2 : cy;
const alpha = toRadians(state.style.rotation ?? 0);
if (alpha !== 0) {
const cos = Math.cos(alpha);
const sin = Math.sin(alpha);
const ct = new Point(state.getCenterX(), state.getCenterY());
const pt = getRotatedPoint(new Point(cx, cy), cos, sin, ct);
cx = pt.x;
cy = pt.y;
}
}
return new Point(cx - icon.bounds!.width / 2, cy - icon.bounds!.height / 2);
}
/**
* Destroys the connect icons and resets the respective state.
*/
destroyIcons() {
for (let i = 0; i < this.icons.length; i += 1) {
this.icons[i].destroy();
}
this.icons = [];
this.icon = null;
this.selectedIcon = null;
this.iconState = null;
}
/**
* Returns true if the given mouse down event should start this handler.
* This implementation returns true if the event does not force marquee
* selection, and the currentConstraint and currentFocus of the
* {@link constraintHandler} are not null, or {@link previous} and {@link error} are not null and
* {@link icons} is null or {@link icons} and {@link icon} are not `null`.
*/
isStartEvent(me: InternalMouseEvent) {
return (
(this.constraintHandler.currentFocus !== null &&
this.constraintHandler.currentConstraint !== null) ||
(this.previous !== null &&
this.error === null &&
(this.icons.length === 0 || this.icon !== null))
);
}
/**
* Handles the event by initiating a new connection.
*/
mouseDown(_sender: EventSource, me: InternalMouseEvent) {
this.mouseDownCounter += 1;
if (
this.isEnabled() &&
this.graph.isEnabled() &&
!me.isConsumed() &&
!this.isConnecting() &&
this.isStartEvent(me)
) {
if (
this.constraintHandler.currentConstraint &&
this.constraintHandler.currentFocus &&
this.constraintHandler.currentPoint
) {
this.sourceConstraint = this.constraintHandler.currentConstraint;
this.previous = this.constraintHandler.currentFocus;
this.first = this.constraintHandler.currentPoint.clone();
} else {
// Stores the location of the initial mousedown
this.first = new Point(me.getGraphX(), me.getGraphY());
}
this.edgeState = this.createEdgeState(me);
this.mouseDownCounter = 1;
if (this.waypointsEnabled && !this.shape) {
this.waypoints = [];
this.shape = this.createShape();
if (this.edgeState) {
this.shape.apply(this.edgeState);
}
}
// Stores the starting point in the geometry of the preview
if (!this.previous && this.edgeState && this.edgeState.cell.geometry) {
const pt = this.graph.getPointForEvent(me.getEvent());
this.edgeState.cell.geometry.setTerminalPoint(pt, true);
}
this.fireEvent(new EventObject(InternalEvent.START, { state: this.previous }));
me.consume();
}
this.selectedIcon = this.icon;
this.icon = null;
}
/**
* Returns true if a tap on the given source state should immediately start
* connecting. This implementation returns true if the state is not movable
* in the graph.
*/
isImmediateConnectSource(state: CellState) {
return !this.graph.isCellMovable(state.cell);
}
/**
* Hook to return an <CellState> which may be used during the preview.
* This implementation returns null.
*
* Use the following code to create a preview for an existing edge style:
*
* ```javascript
* graph.getPlugin('ConnectionHandler').createEdgeState(me)
* {
* var edge = graph.createEdge(null, null, null, null, null, 'edgeStyle=elbowEdgeStyle');
*
* return new CellState(this.graph.view, edge, this.graph.getCellStyle(edge));
* };
* ```
*/
createEdgeState(me?: InternalMouseEvent): CellState | null {
return null;
}
/**
* Returns true if <outlineConnect> is true and the source of the event is the outline shape
* or shift is pressed.
*/
isOutlineConnectEvent(me: InternalMouseEvent) {
if (!this.currentPoint) return false;
const offset = getOffset(this.graph.container);
const evt = me.getEvent();
const clientX = getClientX(evt);
const clientY = getClientY(evt);
const doc = document.documentElement;
const left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
const gridX = this.currentPoint.x - this.graph.container.scrollLeft + offset.x - left;
const gridY = this.currentPoint.y - this.graph.container.scrollTop + offset.y - top;
return (
this.outlineConnect &&
!isShiftDown(me.getEvent()) &&
(me.isSource(this.marker.highlight.shape) ||
(isAltDown(me.getEvent()) && me.getState() != null) ||
this.marker.highlight.isHighlightAt(clientX, clientY) ||
((gridX !== clientX || gridY !== clientY) &&
me.getState() == null &&
this.marker.highlight.isHighlightAt(gridX, gridY)))
);
}
/**
* Updates the current state for a given mouse move event by using the {@link marker}.
*/
updateCurrentState(me: InternalMouseEvent, point: Point): void {
this.constraintHandler.update(
me,
!this.first,
false,
!this.first || me.isSource(this.marker.highlight.shape) ? null : point
);
if (
this.constraintHandler.currentFocus != null &&
this.constraintHandler.currentConstraint != null
) {
// Handles special case where grid is large and connection point is at actual point in which
// case the outline is not followed as long as we're < gridSize / 2 away from that point
if (
this.marker.highlight &&
this.marker.highlight.state &&
this.marker.highlight.state.cell === this.constraintHandler.currentFocus.cell &&
this.marker.highlight.shape
) {
// Direct repaint needed if cell already highlighted
if (this.marker.highlight.shape.stroke !== 'transparent') {
this.marker.highlight.shape.stroke = 'transparent';
this.marker.highlight.repaint();
}
} else {
this.marker.markCell(this.constraintHandler.currentFocus.cell, 'transparent');
}
// Updates validation state
if (this.previous) {
this.error = this.validateConnection(
this.previous.cell,
this.constraintHandler.currentFocus.cell
);
if (!this.error) {
this.currentState = this.constraintHandler.currentFocus;
}
if (
this.error ||
(this.currentState && !this.isCellEnabled(this.currentState.cell))
) {
this.constraintHandler.reset();
}
}
} else {
if (this.graph.isIgnoreTerminalEvent(me.getEvent())) {
this.marker.reset();
this.currentState = null;
} else {
this.marker.process(me);
this.currentState = this.marker.getValidState();
}
if (this.currentState != null && !this.isCellEnabled(this.currentState.cell)) {
this.constraintHandler.reset();
this.marker.reset();
this.currentState = null;
}
const outline = this.isOutlineConnectEvent(me);
if (this.currentState != null && outline) {
// Handles special case where mouse is on outline away from actual end point
// in which case the grid is ignored and mouse point is used instead
if (me.isSource(this.marker.highlight.shape)) {
point = new Point(me.getGraphX(), me.getGraphY());
}
const constraint = this.graph.getOutlineConstraint(point, this.currentState, me);
this.constraintHandler.setFocus(me, this.currentState, false);
this.constraintHandler.currentConstraint = constraint;
this.constraintHandler.currentPoint = point;
}
if (this.outlineConnect) {
if (this.marker.highlight != null && this.marker.highlight.shape != null) {
const s = this.graph.view.scale;
if (
this.constraintHandler.currentConstraint != null &&
this.constraintHandler.currentFocus != null
) {
this.marker.highlight.shape.stroke = OUTLINE_HIGHLIGHT_COLOR;
this.marker.highlight.shape.strokeWidth =
OUTLINE_HIGHLIGHT_STROKEWIDTH / s / s;
this.marker.highlight.repaint();
} else if (this.marker.hasValidState()) {
const cell = me.getCell();
// Handles special case where actual end point of edge and current mouse point
// are not equal (due to grid snapping) and there is no hit on shape or highlight
// but ignores cases where parent is used for non-connectable child cells
if (
cell &&
cell.isConnectable() &&
this.marker.getValidState() !== me.getState()
) {
this.marker.highlight.shape.stroke = 'transparent';
this.currentState = null;
} else {
this.marker.highlight.shape.stroke = VALID_COLOR;
}
this.marker.highlight.shape.strokeWidth = HIGHLIGHT_STROKEWIDTH / s / s;