-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
node.ts
1306 lines (1132 loc) · 35.3 KB
/
node.ts
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
import { ArrayExt, FunctionExt, Dom } from '@antv/x6-common'
import { Rectangle, Point, GeometryUtil } from '@antv/x6-geometry'
import { Config } from '../config'
import { Attr, PortLayout } from '../registry'
import { Cell } from '../model/cell'
import { Node } from '../model/node'
import { Edge } from '../model/edge'
import { PortManager } from '../model/port'
import { CellView } from './cell'
import { EdgeView } from './edge'
import { Markup } from './markup'
import { AttrManager } from './attr'
import { Graph } from '../graph'
export class NodeView<
Entity extends Node = Node,
Options extends NodeView.Options = NodeView.Options,
> extends CellView<Entity, Options> {
protected portsCache: { [id: string]: NodeView.PortCache } = {}
protected get [Symbol.toStringTag]() {
return NodeView.toStringTag
}
protected getContainerClassName() {
const classList = [
super.getContainerClassName(),
this.prefixClassName('node'),
]
if (!this.can('nodeMovable')) {
classList.push(this.prefixClassName('node-immovable'))
}
return classList.join(' ')
}
protected updateClassName(e: Dom.MouseEnterEvent) {
const target = e.target
if (target.hasAttribute('magnet')) {
// port
const className = this.prefixClassName('port-unconnectable')
if (this.can('magnetConnectable')) {
Dom.removeClass(target, className)
} else {
Dom.addClass(target, className)
}
} else {
// node
const className = this.prefixClassName('node-immovable')
if (this.can('nodeMovable')) {
this.removeClass(className)
} else {
this.addClass(className)
}
}
}
isNodeView(): this is NodeView {
return true
}
confirmUpdate(flag: number, options: any = {}) {
let ret = flag
if (this.hasAction(ret, 'ports')) {
this.removePorts()
this.cleanPortsCache()
}
if (this.hasAction(ret, 'render')) {
this.render()
ret = this.removeAction(ret, [
'render',
'update',
'resize',
'translate',
'rotate',
'ports',
'tools',
])
} else {
ret = this.handleAction(
ret,
'resize',
() => this.resize(),
'update', // Resize method is calling `update()` internally
)
ret = this.handleAction(
ret,
'update',
() => this.update(),
// `update()` will render ports when useCSSSelectors are enabled
Config.useCSSSelector ? 'ports' : null,
)
ret = this.handleAction(ret, 'translate', () => this.translate())
ret = this.handleAction(ret, 'rotate', () => this.rotate())
ret = this.handleAction(ret, 'ports', () => this.renderPorts())
ret = this.handleAction(ret, 'tools', () => {
if (this.getFlag('tools') === flag) {
this.renderTools()
} else {
this.updateTools(options)
}
})
}
return ret
}
update(partialAttrs?: Attr.CellAttrs) {
this.cleanCache()
// When CSS selector strings are used, make sure no rule matches port nodes.
if (Config.useCSSSelector) {
this.removePorts()
}
const node = this.cell
const size = node.getSize()
const attrs = node.getAttrs()
this.updateAttrs(this.container, attrs, {
attrs: partialAttrs === attrs ? null : partialAttrs,
rootBBox: new Rectangle(0, 0, size.width, size.height),
selectors: this.selectors,
})
if (Config.useCSSSelector) {
this.renderPorts()
}
}
protected renderMarkup() {
const markup = this.cell.markup
if (markup) {
if (typeof markup === 'string') {
throw new TypeError('Not support string markup.')
}
return this.renderJSONMarkup(markup)
}
throw new TypeError('Invalid node markup.')
}
protected renderJSONMarkup(markup: Markup.JSONMarkup | Markup.JSONMarkup[]) {
const ret = this.parseJSONMarkup(markup, this.container)
this.selectors = ret.selectors
this.container.appendChild(ret.fragment)
}
render() {
this.empty()
this.renderMarkup()
this.resize()
this.updateTransform()
if (!Config.useCSSSelector) {
this.renderPorts()
}
this.renderTools()
return this
}
resize() {
if (this.cell.getAngle()) {
this.rotate()
}
this.update()
}
translate() {
this.updateTransform()
}
rotate() {
this.updateTransform()
}
protected getTranslationString() {
const position = this.cell.getPosition()
return `translate(${position.x},${position.y})`
}
protected getRotationString() {
const angle = this.cell.getAngle()
if (angle) {
const size = this.cell.getSize()
return `rotate(${angle},${size.width / 2},${size.height / 2})`
}
}
protected updateTransform() {
let transform = this.getTranslationString()
const rot = this.getRotationString()
if (rot) {
transform += ` ${rot}`
}
this.container.setAttribute('transform', transform)
}
// #region ports
findPortElem(portId?: string, selector?: string) {
const cache = portId ? this.portsCache[portId] : null
if (!cache) {
return null
}
const portRoot = cache.portContentElement
const portSelectors = cache.portContentSelectors || {}
return this.findOne(selector, portRoot, portSelectors)
}
protected cleanPortsCache() {
this.portsCache = {}
}
protected removePorts() {
Object.values(this.portsCache).forEach((cached) => {
Dom.remove(cached.portElement)
})
}
protected renderPorts() {
const container = this.container
// References to rendered elements without z-index
const references: Element[] = []
container.childNodes.forEach((child) => {
references.push(child as Element)
})
const parsedPorts = this.cell.getParsedPorts()
const portsGropsByZ = ArrayExt.groupBy(parsedPorts, 'zIndex')
const autoZIndexKey = 'auto'
// render non-z first
if (portsGropsByZ[autoZIndexKey]) {
portsGropsByZ[autoZIndexKey].forEach((port) => {
const portElement = this.getPortElement(port)
container.append(portElement)
references.push(portElement)
})
}
Object.keys(portsGropsByZ).forEach((key) => {
if (key !== autoZIndexKey) {
const zIndex = parseInt(key, 10)
this.appendPorts(portsGropsByZ[key], zIndex, references)
}
})
this.updatePorts()
}
protected appendPorts(
ports: PortManager.Port[],
zIndex: number,
refs: Element[],
) {
const elems = ports.map((p) => this.getPortElement(p))
if (refs[zIndex] || zIndex < 0) {
Dom.before(refs[Math.max(zIndex, 0)], elems)
} else {
Dom.append(this.container, elems)
}
}
protected getPortElement(port: PortManager.Port) {
const cached = this.portsCache[port.id]
if (cached) {
return cached.portElement
}
return this.createPortElement(port)
}
protected createPortElement(port: PortManager.Port) {
let renderResult = Markup.renderMarkup(this.cell.getPortContainerMarkup())
const portElement = renderResult.elem
if (portElement == null) {
throw new Error('Invalid port container markup.')
}
renderResult = Markup.renderMarkup(this.getPortMarkup(port))
const portContentElement = renderResult.elem
const portContentSelectors = renderResult.selectors
if (portContentElement == null) {
throw new Error('Invalid port markup.')
}
this.setAttrs(
{
port: port.id,
'port-group': port.group,
},
portContentElement,
)
let portClass = 'x6-port'
if (port.group) {
portClass += ` x6-port-${port.group}`
}
Dom.addClass(portElement, portClass)
Dom.addClass(portElement, 'x6-port')
Dom.addClass(portContentElement, 'x6-port-body')
portElement.appendChild(portContentElement)
let portSelectors: Markup.Selectors | undefined = portContentSelectors
let portLabelElement: Element | undefined
let portLabelSelectors: Markup.Selectors | null | undefined
const existLabel = this.existPortLabel(port)
if (existLabel) {
renderResult = Markup.renderMarkup(this.getPortLabelMarkup(port.label))
portLabelElement = renderResult.elem
portLabelSelectors = renderResult.selectors
if (portLabelElement == null) {
throw new Error('Invalid port label markup.')
}
if (portContentSelectors && portLabelSelectors) {
// eslint-disable-next-line
for (const key in portLabelSelectors) {
if (portContentSelectors[key] && key !== this.rootSelector) {
throw new Error('Selectors within port must be unique.')
}
}
portSelectors = {
...portContentSelectors,
...portLabelSelectors,
}
}
Dom.addClass(portLabelElement, 'x6-port-label')
portElement.appendChild(portLabelElement)
}
this.portsCache[port.id] = {
portElement,
portSelectors,
portLabelElement,
portLabelSelectors,
portContentElement,
portContentSelectors,
}
if (this.graph.options.onPortRendered) {
this.graph.options.onPortRendered({
port,
node: this.cell,
container: portElement,
selectors: portSelectors,
labelContainer: portLabelElement,
labelSelectors: portLabelSelectors,
contentContainer: portContentElement,
contentSelectors: portContentSelectors,
})
}
return portElement
}
protected updatePorts() {
const groups = this.cell.getParsedGroups()
const groupList = Object.keys(groups)
if (groupList.length === 0) {
this.updatePortGroup()
} else {
groupList.forEach((groupName) => this.updatePortGroup(groupName))
}
}
protected updatePortGroup(groupName?: string) {
const bbox = Rectangle.fromSize(this.cell.getSize())
const metrics = this.cell.getPortsLayoutByGroup(groupName, bbox)
for (let i = 0, n = metrics.length; i < n; i += 1) {
const metric = metrics[i]
const portId = metric.portId
const cached = this.portsCache[portId] || {}
const portLayout = metric.portLayout
this.applyPortTransform(cached.portElement, portLayout)
if (metric.portAttrs != null) {
const options: Partial<AttrManager.UpdateOptions> = {
selectors: cached.portSelectors || {},
}
if (metric.portSize) {
options.rootBBox = Rectangle.fromSize(metric.portSize)
}
this.updateAttrs(cached.portElement, metric.portAttrs, options)
}
const labelLayout = metric.labelLayout
if (labelLayout && cached.portLabelElement) {
this.applyPortTransform(
cached.portLabelElement,
labelLayout,
-(portLayout.angle || 0),
)
if (labelLayout.attrs) {
const options: Partial<AttrManager.UpdateOptions> = {
selectors: cached.portLabelSelectors || {},
}
if (metric.labelSize) {
options.rootBBox = Rectangle.fromSize(metric.labelSize)
}
this.updateAttrs(cached.portLabelElement, labelLayout.attrs, options)
}
}
}
}
protected applyPortTransform(
element: Element,
layout: PortLayout.Result,
initialAngle = 0,
) {
const angle = layout.angle
const position = layout.position
const matrix = Dom.createSVGMatrix()
.rotate(initialAngle)
.translate(position.x || 0, position.y || 0)
.rotate(angle || 0)
Dom.transform(element as SVGElement, matrix, { absolute: true })
}
protected getPortMarkup(port: PortManager.Port) {
return port.markup || this.cell.portMarkup
}
protected getPortLabelMarkup(label: PortManager.Label) {
return label.markup || this.cell.portLabelMarkup
}
protected existPortLabel(port: PortManager.Port) {
return port.attrs && port.attrs.text
}
// #endregion
// #region events
protected getEventArgs<E>(e: E): NodeView.MouseEventArgs<E>
protected getEventArgs<E>(
e: E,
x: number,
y: number,
): NodeView.PositionEventArgs<E>
protected getEventArgs<E>(e: E, x?: number, y?: number) {
const view = this // eslint-disable-line
const node = view.cell
const cell = node
if (x == null || y == null) {
return { e, view, node, cell } as NodeView.MouseEventArgs<E>
}
return { e, x, y, view, node, cell } as NodeView.PositionEventArgs<E>
}
protected getPortEventArgs<E>(
e: E,
port: string,
pos?: { x: number; y: number },
): NodeView.PositionEventArgs<E> | NodeView.MouseEventArgs<E> {
const view = this // eslint-disable-line
const node = view.cell
const cell = node
if (pos) {
return {
e,
x: pos.x,
y: pos.y,
view,
node,
cell,
port,
} as NodeView.PositionEventArgs<E>
}
return { e, view, node, cell, port } as NodeView.MouseEventArgs<E>
}
notifyMouseDown(e: Dom.MouseDownEvent, x: number, y: number) {
super.onMouseDown(e, x, y)
this.notify('node:mousedown', this.getEventArgs(e, x, y))
}
notifyMouseMove(e: Dom.MouseMoveEvent, x: number, y: number) {
super.onMouseMove(e, x, y)
this.notify('node:mousemove', this.getEventArgs(e, x, y))
}
notifyMouseUp(e: Dom.MouseUpEvent, x: number, y: number) {
super.onMouseUp(e, x, y)
this.notify('node:mouseup', this.getEventArgs(e, x, y))
}
notifyPortEvent(
name: string,
e: Dom.EventObject,
pos?: { x: number; y: number },
) {
const port = this.findAttr('port', e.target)
if (port) {
const originType = e.type
if (name === 'node:port:mouseenter') {
e.type = 'mouseenter'
} else if (name === 'node:port:mouseleave') {
e.type = 'mouseleave'
}
this.notify(name, this.getPortEventArgs(e, port, pos))
e.type = originType
}
}
onClick(e: Dom.ClickEvent, x: number, y: number) {
super.onClick(e, x, y)
this.notify('node:click', this.getEventArgs(e, x, y))
this.notifyPortEvent('node:port:click', e, { x, y })
}
onDblClick(e: Dom.DoubleClickEvent, x: number, y: number) {
super.onDblClick(e, x, y)
this.notify('node:dblclick', this.getEventArgs(e, x, y))
this.notifyPortEvent('node:port:dblclick', e, { x, y })
}
onContextMenu(e: Dom.ContextMenuEvent, x: number, y: number) {
super.onContextMenu(e, x, y)
this.notify('node:contextmenu', this.getEventArgs(e, x, y))
this.notifyPortEvent('node:port:contextmenu', e, { x, y })
}
onMouseDown(e: Dom.MouseDownEvent, x: number, y: number) {
if (this.isPropagationStopped(e)) {
return
}
this.notifyMouseDown(e, x, y)
this.notifyPortEvent('node:port:mousedown', e, { x, y })
this.startNodeDragging(e, x, y)
}
onMouseMove(e: Dom.MouseMoveEvent, x: number, y: number) {
const data = this.getEventData<EventData.Mousemove>(e)
const action = data.action
if (action === 'magnet') {
this.dragMagnet(e, x, y)
} else {
if (action === 'move') {
const meta = data as EventData.Moving
const view = meta.targetView || this
view.dragNode(e, x, y)
view.notify('node:moving', {
e,
x,
y,
view,
cell: view.cell,
node: view.cell,
})
}
this.notifyMouseMove(e, x, y)
this.notifyPortEvent('node:port:mousemove', e, { x, y })
}
this.setEventData<EventData.Mousemove>(e, data)
}
onMouseUp(e: Dom.MouseUpEvent, x: number, y: number) {
const data = this.getEventData<EventData.Mousemove>(e)
const action = data.action
if (action === 'magnet') {
this.stopMagnetDragging(e, x, y)
} else {
this.notifyMouseUp(e, x, y)
this.notifyPortEvent('node:port:mouseup', e, { x, y })
if (action === 'move') {
const meta = data as EventData.Moving
const view = meta.targetView || this
view.stopNodeDragging(e, x, y)
}
}
const magnet = (data as EventData.Magnet).targetMagnet
if (magnet) {
this.onMagnetClick(e, magnet, x, y)
}
this.checkMouseleave(e)
}
onMouseOver(e: Dom.MouseOverEvent) {
super.onMouseOver(e)
this.notify('node:mouseover', this.getEventArgs(e))
// mock mouseenter event,so we can get correct trigger time when move mouse from node to port
// wo also need to change e.type for use get correct event args
this.notifyPortEvent('node:port:mouseenter', e)
this.notifyPortEvent('node:port:mouseover', e)
}
onMouseOut(e: Dom.MouseOutEvent) {
super.onMouseOut(e)
this.notify('node:mouseout', this.getEventArgs(e))
// mock mouseleave event,so we can get correct trigger time when move mouse from port to node
// wo also need to change e.type for use get correct event args
this.notifyPortEvent('node:port:mouseleave', e)
this.notifyPortEvent('node:port:mouseout', e)
}
onMouseEnter(e: Dom.MouseEnterEvent) {
this.updateClassName(e)
super.onMouseEnter(e)
this.notify('node:mouseenter', this.getEventArgs(e))
}
onMouseLeave(e: Dom.MouseLeaveEvent) {
super.onMouseLeave(e)
this.notify('node:mouseleave', this.getEventArgs(e))
}
onMouseWheel(e: Dom.EventObject, x: number, y: number, delta: number) {
super.onMouseWheel(e, x, y, delta)
this.notify('node:mousewheel', {
delta,
...this.getEventArgs(e, x, y),
})
}
onMagnetClick(e: Dom.MouseUpEvent, magnet: Element, x: number, y: number) {
const graph = this.graph
const count = graph.view.getMouseMovedCount(e)
if (count > graph.options.clickThreshold) {
return
}
this.notify('node:magnet:click', {
magnet,
...this.getEventArgs(e, x, y),
})
}
onMagnetDblClick(
e: Dom.DoubleClickEvent,
magnet: Element,
x: number,
y: number,
) {
this.notify('node:magnet:dblclick', {
magnet,
...this.getEventArgs(e, x, y),
})
}
onMagnetContextMenu(
e: Dom.ContextMenuEvent,
magnet: Element,
x: number,
y: number,
) {
this.notify('node:magnet:contextmenu', {
magnet,
...this.getEventArgs(e, x, y),
})
}
onMagnetMouseDown(
e: Dom.MouseDownEvent,
magnet: Element,
x: number,
y: number,
) {
this.startMagnetDragging(e, x, y)
}
onCustomEvent(e: Dom.MouseDownEvent, name: string, x: number, y: number) {
this.notify('node:customevent', { name, ...this.getEventArgs(e, x, y) })
super.onCustomEvent(e, name, x, y)
}
protected prepareEmbedding(e: Dom.MouseMoveEvent) {
const graph = this.graph
const data = this.getEventData<EventData.MovingTargetNode>(e)
const node = data.cell || this.cell
const view = graph.findViewByCell(node)
const localPoint = graph.snapToGrid(e.clientX, e.clientY)
this.notify('node:embed', {
e,
node,
view,
cell: node,
x: localPoint.x,
y: localPoint.y,
currentParent: node.getParent(),
})
}
processEmbedding(e: Dom.MouseMoveEvent, data: EventData.MovingTargetNode) {
const cell = data.cell || this.cell
const graph = data.graph || this.graph
const options = graph.options.embedding
const findParent = options.findParent
let candidates =
typeof findParent === 'function'
? (
FunctionExt.call(findParent, graph, {
view: this,
node: this.cell,
}) as Cell[]
).filter((c) => {
return (
Cell.isCell(c) &&
this.cell.id !== c.id &&
!c.isDescendantOf(this.cell)
)
})
: graph.model.getNodesUnderNode(cell, {
by: findParent as Rectangle.KeyPoint,
})
// Picks the node with the highest `z` index
if (options.frontOnly) {
if (candidates.length > 0) {
const zIndexMap = ArrayExt.groupBy(candidates, 'zIndex')
const maxZIndex = ArrayExt.max(
Object.keys(zIndexMap).map((z) => parseInt(z, 10)),
)
if (maxZIndex) {
candidates = zIndexMap[maxZIndex]
}
}
}
// Filter the nodes which is invisiable
candidates = candidates.filter((candidate) => candidate.visible)
let newCandidateView = null
const prevCandidateView = data.candidateEmbedView
const validateEmbeding = options.validate
for (let i = candidates.length - 1; i >= 0; i -= 1) {
const candidate = candidates[i]
if (prevCandidateView && prevCandidateView.cell.id === candidate.id) {
// candidate remains the same
newCandidateView = prevCandidateView
break
} else {
const view = candidate.findView(graph) as NodeView
if (
validateEmbeding &&
FunctionExt.call(validateEmbeding, graph, {
child: this.cell,
parent: view.cell,
childView: this,
parentView: view,
})
) {
// flip to the new candidate
newCandidateView = view
break
}
}
}
this.clearEmbedding(data)
if (newCandidateView) {
newCandidateView.highlight(null, { type: 'embedding' })
}
data.candidateEmbedView = newCandidateView
const localPoint = graph.snapToGrid(e.clientX, e.clientY)
this.notify('node:embedding', {
e,
cell,
node: cell,
view: graph.findViewByCell(cell),
x: localPoint.x,
y: localPoint.y,
currentParent: cell.getParent(),
candidateParent: newCandidateView ? newCandidateView.cell : null,
})
}
clearEmbedding(data: EventData.MovingTargetNode) {
const candidateView = data.candidateEmbedView
if (candidateView) {
candidateView.unhighlight(null, { type: 'embedding' })
data.candidateEmbedView = null
}
}
finalizeEmbedding(e: Dom.MouseUpEvent, data: EventData.MovingTargetNode) {
this.graph.startBatch('embedding')
const cell = data.cell || this.cell
const graph = data.graph || this.graph
const view = graph.findViewByCell(cell)
const parent = cell.getParent()
const candidateView = data.candidateEmbedView
if (candidateView) {
// Candidate view is chosen to become the parent of the node.
candidateView.unhighlight(null, { type: 'embedding' })
data.candidateEmbedView = null
if (parent == null || parent.id !== candidateView.cell.id) {
candidateView.cell.insertChild(cell, undefined, { ui: true })
}
} else if (parent) {
parent.unembed(cell, { ui: true })
}
graph.model.getConnectedEdges(cell, { deep: true }).forEach((edge) => {
edge.updateParent({ ui: true })
})
if (view && candidateView) {
const localPoint = graph.snapToGrid(e.clientX, e.clientY)
view.notify('node:embedded', {
e,
cell,
x: localPoint.x,
y: localPoint.y,
node: cell,
view: graph.findViewByCell(cell),
previousParent: parent,
currentParent: cell.getParent(),
})
}
this.graph.stopBatch('embedding')
}
getDelegatedView() {
let cell = this.cell
let view: NodeView = this // eslint-disable-line
while (view) {
if (cell.isEdge()) {
break
}
if (!cell.hasParent() || view.can('stopDelegateOnDragging')) {
return view
}
cell = cell.getParent() as Entity
view = this.graph.findViewByCell(cell) as NodeView
}
return null
}
protected validateMagnet(
cellView: CellView,
magnet: Element,
e: Dom.MouseDownEvent | Dom.MouseEnterEvent,
) {
if (magnet.getAttribute('magnet') !== 'passive') {
const validate = this.graph.options.connecting.validateMagnet
if (validate) {
return FunctionExt.call(validate, this.graph, {
e,
magnet,
view: cellView,
cell: cellView.cell,
})
}
return true
}
return false
}
protected startMagnetDragging(e: Dom.MouseDownEvent, x: number, y: number) {
if (!this.can('magnetConnectable')) {
return
}
e.stopPropagation()
const magnet = e.currentTarget
const graph = this.graph
this.setEventData<Partial<EventData.Magnet>>(e, {
targetMagnet: magnet,
})
if (this.validateMagnet(this, magnet, e)) {
if (graph.options.magnetThreshold <= 0) {
this.startConnectting(e, magnet, x, y)
}
this.setEventData<Partial<EventData.Magnet>>(e, {
action: 'magnet',
})
this.stopPropagation(e)
} else {
this.onMouseDown(e, x, y)
}
graph.view.delegateDragEvents(e, this)
}
protected startConnectting(
e: Dom.MouseDownEvent,
magnet: Element,
x: number,
y: number,
) {
this.graph.model.startBatch('add-edge')
const edgeView = this.createEdgeFromMagnet(magnet, x, y)
edgeView.setEventData(
e,
edgeView.prepareArrowheadDragging('target', {
x,
y,
isNewEdge: true,
fallbackAction: 'remove',
}),
)
this.setEventData<Partial<EventData.Magnet>>(e, { edgeView })
edgeView.notifyMouseDown(e, x, y)
}
protected getDefaultEdge(sourceView: CellView, sourceMagnet: Element) {
let edge: Edge | undefined | null | void
const create = this.graph.options.connecting.createEdge
if (create) {
edge = FunctionExt.call(create, this.graph, {
sourceMagnet,
sourceView,
sourceCell: sourceView.cell,
})
}
return edge as Edge
}
protected createEdgeFromMagnet(magnet: Element, x: number, y: number) {
const graph = this.graph
const model = graph.model
const edge = this.getDefaultEdge(this, magnet)
edge.setSource({
...edge.getSource(),
...this.getEdgeTerminal(magnet, x, y, edge, 'source'),
})
edge.setTarget({ ...edge.getTarget(), x, y })
edge.addTo(model, { async: false, ui: true })
return edge.findView(graph) as EdgeView
}
protected dragMagnet(e: Dom.MouseMoveEvent, x: number, y: number) {
const data = this.getEventData<EventData.Magnet>(e)
const edgeView = data.edgeView
if (edgeView) {
edgeView.onMouseMove(e, x, y)
this.autoScrollGraph(e.clientX, e.clientY)
} else {
const graph = this.graph
const magnetThreshold = graph.options.magnetThreshold as any
const currentTarget = this.getEventTarget(e)
const targetMagnet = data.targetMagnet
// magnetThreshold when the pointer leaves the magnet
if (magnetThreshold === 'onleave') {
if (
targetMagnet === currentTarget ||
targetMagnet.contains(currentTarget)
) {
return
}
// eslint-disable-next-line no-lonely-if
} else {
// magnetThreshold defined as a number of movements
if (graph.view.getMouseMovedCount(e) <= magnetThreshold) {
return
}
}
this.startConnectting(e as any, targetMagnet, x, y)
}
}
protected stopMagnetDragging(e: Dom.MouseUpEvent, x: number, y: number) {
const data = this.eventData<EventData.Magnet>(e)
const edgeView = data.edgeView
if (edgeView) {
edgeView.onMouseUp(e, x, y)
this.graph.model.stopBatch('add-edge')
}
}
protected notifyUnhandledMouseDown(
e: Dom.MouseDownEvent,
x: number,
y: number,
) {
this.notify('node:unhandled:mousedown', {
e,