-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathGraphModel.ts
1713 lines (1601 loc) · 48.4 KB
/
GraphModel.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 { find, forEach, map, merge, isBoolean, debounce, isEqual } from 'lodash-es'
import { action, computed, observable } from 'mobx'
import {
BaseEdgeModel,
BaseNodeModel,
EditConfigModel,
Model,
PolylineEdgeModel,
TransformModel,
} from '.'
import {
DEFAULT_VISIBLE_SPACE,
ELEMENT_MAX_Z_INDEX,
ElementState,
ElementType,
EventType,
ModelType,
OverlapMode,
TextMode,
} from '../constant'
import LogicFlow from '../LogicFlow'
import { Options as LFOptions } from '../options'
import {
createEdgeGenerator,
createUuid,
formatData,
getClosestPointOfPolyline,
getMinIndex,
getNodeAnchorPosition,
getNodeBBox,
getZIndex,
isPointInArea,
setupAnimation,
setupTheme,
snapToGrid,
updateTheme,
} from '../util'
import EventEmitter from '../event/eventEmitter'
import { Grid } from '../view/overlay'
import Position = LogicFlow.Position
import PointTuple = LogicFlow.PointTuple
import GraphData = LogicFlow.GraphData
import NodeConfig = LogicFlow.NodeConfig
import AnchorConfig = Model.AnchorConfig
import BaseNodeModelCtor = LogicFlow.BaseNodeModelCtor
import BaseEdgeModelCtor = LogicFlow.BaseEdgeModelCtor
export class GraphModel {
/**
* LogicFlow画布挂载元素
* 也就是初始化LogicFlow实例时传入的container
*/
public readonly rootEl: HTMLElement
readonly flowId?: string // 流程图 ID
@observable width: number // 画布宽度
@observable height: number // 画布高度
// 流程图主题配置
theme: LogicFlow.Theme
// 网格配置
@observable grid: Grid.GridOptions
// 事件中心
readonly eventCenter: EventEmitter
// 维护所有节点和边类型对应的 model
readonly modelMap: Map<string, LogicFlow.GraphElementCtor> = new Map()
/**
* 位于当前画布顶部的元素
* 此元素只在堆叠模式为默认模式下存在
* 用于在默认模式下将之前的顶部元素回复初始高度
*/
topElement?: BaseNodeModel | BaseEdgeModel
// 控制是否开启动画
animation?: boolean | LFOptions.AnimationConfig
// 自定义全局 id 生成器
idGenerator?: (type?: string) => string | undefined
// 节点间连线、连线变更时的边的生成规则
edgeGenerator: LFOptions.Definition['edgeGenerator']
// Remind:用于记录当前画布上所有节点和边的 model 的 Map
// 现在的处理方式,用 this.nodes.map 生成的方式,如果在 new Model 的过程中依赖于其它节点的 model,会出现找不到的情况
// eg: new DynamicGroupModel 时,需要获取当前 children 的 model,根据 groupModel 的 isCollapsed 状态更新子节点的 visible
nodeModelMap: Map<string, BaseNodeModel> = new Map()
edgeModelMap: Map<string, BaseEdgeModel> = new Map()
elementsModelMap: Map<string, BaseNodeModel | BaseEdgeModel> = new Map()
/**
* 节点移动规则判断
* 在节点移动的时候,会触发此数组中的所有规则判断
*/
nodeMoveRules: Model.NodeMoveRule[] = []
/**
* 节点resize规则判断
* 在节点resize的时候,会触发此数组中的所有规则判断
*/
nodeResizeRules: Model.NodeResizeRule[] = []
/**
* 获取自定义连线轨迹
*/
customTrajectory: LFOptions.Definition['customTrajectory']
// 在图上操作创建边时,默认使用的边类型.
@observable edgeType: string
// 当前图上所有节点的model
@observable nodes: BaseNodeModel[] = []
// 当前图上所有边的model
@observable edges: BaseEdgeModel[] = []
// 外部拖动节点进入画布的过程中,用fakeNode来和画布上正是的节点区分开
@observable fakeNode?: BaseNodeModel | null
/**
* 元素重合时堆叠模式:
* - DEFAULT(默认模式):节点和边被选中,会被显示在最上面。当取消选中后,元素会恢复之前的层级
* - INCREASE(递增模式):节点和边被选中,会被显示在最上面。当取消选中后,元素会保持当前层级
*/
@observable overlapMode = OverlapMode.DEFAULT
// 背景配置
@observable background?: boolean | LFOptions.BackgroundConfig
// 网格大小
@observable gridSize: number = 1
// 控制画布的缩放、平移
@observable transformModel: TransformModel
// 控制流程图编辑相关配置项 Model
@observable editConfigModel: EditConfigModel
// 控制是否开启局部渲染
@observable partial: boolean = false;
// 用户自定义属性
[propName: string]: any
private waitCleanEffects: (() => void)[] = []
constructor(options: LFOptions.Common) {
const {
container,
partial,
background = {},
grid,
idGenerator,
edgeGenerator,
animation,
customTrajectory,
} = options
this.rootEl = container
this.partial = !!partial
this.background = background
if (typeof grid === 'object') {
this.gridSize = grid.size || 1 // 默认 gridSize 设置为 1
}
this.theme = setupTheme(options.style)
this.grid = Grid.getGridOptions(grid ?? false)
this.edgeType = options.edgeType || 'polyline'
this.animation = setupAnimation(animation)
this.overlapMode = options.overlapMode || OverlapMode.DEFAULT
this.width = options.width || this.rootEl.getBoundingClientRect().width
this.height = options.height || this.rootEl.getBoundingClientRect().height
const resizeObserver = new ResizeObserver(
debounce(
((entries) => {
for (const entry of entries) {
if (entry.target === this.rootEl) {
this.resize()
this.eventCenter.emit('graph:resize', {
target: this.rootEl,
contentRect: entry.contentRect,
})
}
}
}) as ResizeObserverCallback,
16,
),
)
resizeObserver.observe(this.rootEl)
this.waitCleanEffects.push(() => {
resizeObserver.disconnect()
})
this.eventCenter = new EventEmitter()
this.editConfigModel = new EditConfigModel(options)
this.transformModel = new TransformModel(this.eventCenter, options)
this.flowId = createUuid()
this.idGenerator = idGenerator
this.edgeGenerator = createEdgeGenerator(this, edgeGenerator)
this.customTrajectory = customTrajectory
}
@computed get nodesMap(): GraphModel.NodesMapType {
return this.nodes.reduce((nMap, model, index) => {
nMap[model.id] = {
index,
model,
}
return nMap
}, {} as GraphModel.NodesMapType)
}
@computed get edgesMap(): GraphModel.EdgesMapType {
return this.edges.reduce((eMap, model, index) => {
eMap[model.id] = {
index,
model,
}
return eMap
}, {})
}
@computed get modelsMap(): GraphModel.ModelsMapType {
return [...this.nodes, ...this.edges].reduce((eMap, model) => {
eMap[model.id] = model
return eMap
}, {})
}
/**
* 基于zIndex对元素进行排序。
* todo: 性能优化
*/
@computed get sortElements() {
const elements = [...this.nodes, ...this.edges].sort(
(a, b) => a.zIndex - b.zIndex,
)
// 只显示可见区域的节点和边
const visibleElements: (BaseNodeModel | BaseEdgeModel)[] = []
// TODO: 缓存,优化计算效率 by xutao. So how?
const visibleLt: PointTuple = [
-DEFAULT_VISIBLE_SPACE,
-DEFAULT_VISIBLE_SPACE,
]
const visibleRb: PointTuple = [
this.width + DEFAULT_VISIBLE_SPACE,
this.height + DEFAULT_VISIBLE_SPACE,
]
for (let i = 0; i < elements.length; i++) {
const currentItem = elements[i]
// 如果节点不在可见区域,且不是全元素显示模式,则隐藏节点。
if (
currentItem.visible &&
(!this.partial ||
currentItem.isSelected ||
this.isElementInArea(currentItem, visibleLt, visibleRb, false, false))
) {
visibleElements.push(currentItem)
}
}
return visibleElements
}
/**
* 当前编辑的元素,低频操作,先循环找。
*/
@computed get textEditElement() {
const textEditNode = this.nodes.find(
(node) => node.state === ElementState.TEXT_EDIT,
)
const textEditEdge = this.edges.find(
(edge) => edge.state === ElementState.TEXT_EDIT,
)
return textEditNode || textEditEdge
}
/**
* 当前画布所有被选中的元素
*/
@computed get selectElements() {
const elements = new Map<string, BaseNodeModel | BaseEdgeModel>()
this.nodes.forEach((node) => {
if (node.isSelected) {
elements.set(node.id, node)
}
})
this.edges.forEach((edge) => {
if (edge.isSelected) {
elements.set(edge.id, edge)
}
})
return elements
}
@computed get selectNodes() {
const nodes: BaseNodeModel[] = []
this.nodes.forEach((node) => {
if (node.isSelected) {
nodes.push(node)
}
})
return nodes
}
/**
* 获取指定区域内的所有元素
* @param leftTopPoint 表示区域左上角的点
* @param rightBottomPoint 表示区域右下角的点
* @param wholeEdge 是否要整个边都在区域内部
* @param wholeNode 是否要整个节点都在区域内部
* @param ignoreHideElement 是否忽略隐藏的节点
*/
// TODO: rename getAreaElement to getElementsInArea or getAreaElements
getAreaElement(
leftTopPoint: PointTuple,
rightBottomPoint: PointTuple,
wholeEdge = true,
wholeNode = true,
ignoreHideElement = false,
) {
const areaElements: LogicFlow.GraphElement[] = []
forEach([...this.nodes, ...this.edges], (element) => {
const isElementInArea = this.isElementInArea(
element,
leftTopPoint,
rightBottomPoint,
wholeEdge,
wholeNode,
)
if ((!ignoreHideElement || element.visible) && isElementInArea) {
areaElements.push(element)
}
})
return areaElements
}
/**
* 获取指定类型元素对应的Model
*/
getModel(type: string) {
return this.modelMap.get(type)
}
/**
* 基于Id获取节点的model
*/
getNodeModelById(nodeId: string): BaseNodeModel | undefined {
if (this.fakeNode && nodeId === this.fakeNode.id) {
return this.fakeNode
}
return this.nodesMap[nodeId]?.model
}
/**
* 因为流程图所在的位置可以是页面任何地方
* 当内部事件需要获取触发事件时,其相对于画布左上角的位置
* 需要事件触发位置减去画布相对于client的位置
*/
getPointByClient({
x: x1,
y: y1,
}: LogicFlow.Point): LogicFlow.ClientPosition {
const bbox = this.rootEl.getBoundingClientRect()
const domOverlayPosition: Position = {
x: x1 - bbox.left,
y: y1 - bbox.top,
}
const [x, y] = this.transformModel.HtmlPointToCanvasPoint([
domOverlayPosition.x,
domOverlayPosition.y,
])
const canvasOverlayPosition: Position = { x, y }
return {
domOverlayPosition,
canvasOverlayPosition,
}
}
/**
* 判断一个元素是否在指定矩形区域内。
* @param element 节点或者边
* @param lt 左上角点
* @param rb 右下角点
* @param wholeEdge 边的起点和终点都在区域内才算
* @param wholeNode 节点的box都在区域内才算
*/
isElementInArea(
element: BaseEdgeModel | BaseNodeModel,
lt: PointTuple,
rb: PointTuple,
wholeEdge = true,
wholeNode = true,
) {
if (element.BaseType === ElementType.NODE) {
element = element as BaseNodeModel
// 节点是否在选区内,判断逻辑为如果节点的bbox的四个角上的点都在选区内,则判断节点在选区内
const { minX, minY, maxX, maxY } = getNodeBBox(element)
const bboxPointsList: Position[] = [
{
x: minX,
y: minY,
},
{
x: maxX,
y: minY,
},
{
x: maxX,
y: maxY,
},
{
x: minX,
y: maxY,
},
]
let inArea = wholeNode
for (let i = 0; i < bboxPointsList.length; i++) {
let { x, y } = bboxPointsList[i]
;[x, y] = this.transformModel.CanvasPointToHtmlPoint([x, y])
if (isPointInArea([x, y], lt, rb) !== wholeNode) {
inArea = !wholeNode
break
}
}
return inArea
}
if (element.BaseType === ElementType.EDGE) {
element = element as BaseEdgeModel
const { startPoint, endPoint } = element
const startHtmlPoint = this.transformModel.CanvasPointToHtmlPoint([
startPoint.x,
startPoint.y,
])
const endHtmlPoint = this.transformModel.CanvasPointToHtmlPoint([
endPoint.x,
endPoint.y,
])
const isStartInArea = isPointInArea(startHtmlPoint, lt, rb)
const isEndInArea = isPointInArea(endHtmlPoint, lt, rb)
return wholeEdge
? isStartInArea && isEndInArea
: isStartInArea || isEndInArea
}
return false
}
/**
* 使用新的数据重新设置整个画布的元素
* 注意:将会清除画布上所有已有的节点和边
* @param { object } graphData 图数据
*/
graphDataToModel(graphData: Partial<LogicFlow.GraphConfigData>) {
if (!this.width || !this.height) {
this.resize()
}
if (!graphData) {
this.nodes = []
this.edges = []
return
}
if (graphData.nodes) {
this.nodes = map(graphData.nodes, (node: NodeConfig) =>
this.getModelAfterSnapToGrid(node),
)
} else {
this.nodes = []
}
if (graphData.edges) {
const currEdgeType = this.edgeType
this.edges = map(graphData.edges, (edge) => {
const Model = this.getModel(
edge.type ?? currEdgeType,
) as BaseEdgeModelCtor
if (!Model) {
throw new Error(`找不到${edge.type}对应的边。`)
}
const edgeModel = new Model(edge, this)
// 根据edgeModel中存储的数据找到当前画布上的起终锚点坐标
// 判断当前起终锚点数据和Model中存储的起终点数据是否一致,不一致更新起终点信息
const {
sourceNodeId,
targetNodeId,
sourceAnchorId = '',
targetAnchorId = '',
startPoint,
endPoint,
text,
textPosition,
} = edgeModel
const updateAnchorPoint = (
node: BaseNodeModel | undefined,
anchorId: string,
point: Position,
updatePoint: (anchor: AnchorConfig) => void,
) => {
const anchor = node?.anchors.find((anchor) => anchor.id === anchorId)
if (anchor && !isEqual(anchor, point)) {
updatePoint(anchor)
}
}
const sourceNode = this.getNodeModelById(sourceNodeId)
const targetNode = this.getNodeModelById(targetNodeId)
updateAnchorPoint(
sourceNode,
sourceAnchorId,
startPoint,
edgeModel.updateStartPoint.bind(edgeModel),
)
updateAnchorPoint(
targetNode,
targetAnchorId,
endPoint,
edgeModel.updateEndPoint.bind(edgeModel),
)
// 而文本需要先算一下文本与默认文本位置之间的相对位置差
// 再计算新路径的文本默认位置,加上相对位置差,得到调整后边的文本的位置
if (text) {
const { x, y } = text
const { x: defaultX, y: defaultY } = textPosition
if (x && y && defaultX && defaultY) {
const deltaX = x - defaultX
const deltaY = y - defaultY
edgeModel.resetTextPosition()
edgeModel.moveText(deltaX, deltaY)
}
}
this.edgeModelMap.set(edgeModel.id, edgeModel)
this.elementsModelMap.set(edgeModel.id, edgeModel)
return edgeModel
})
} else {
this.edges = []
}
}
/**
* 获取画布数据
*/
modelToGraphData(): GraphData {
const edges: LogicFlow.EdgeData[] = []
this.edges.forEach((edge) => {
const data = edge.getData()
if (data && !edge.virtual) edges.push(data)
})
const nodes: LogicFlow.NodeData[] = []
this.nodes.forEach((node) => {
const data = node.getData()
if (data && !node.virtual) nodes.push(data)
})
return {
nodes,
edges,
}
}
// 用户history记录的数据,忽略拖拽过程中的数据变更
modelToHistoryData(): GraphData | false {
let nodeDragging = false
const nodes: LogicFlow.NodeData[] = []
// 如果有节点在拖拽中,不更新history
for (let i = 0; i < this.nodes.length; i++) {
const nodeModel = this.nodes[i]
if (nodeModel.isDragging) {
nodeDragging = true
break
} else {
nodes.push(nodeModel.getHistoryData())
}
}
if (nodeDragging) {
return false
}
// 如果有边在拖拽中,不更新history
let edgeDragging = false
const edges: LogicFlow.EdgeData[] = []
for (let j = 0; j < this.edges.length; j++) {
const edgeMode = this.edges[j]
if (edgeMode.isDragging) {
edgeDragging = true
break
} else {
edges.push(edgeMode.getHistoryData())
}
}
if (edgeDragging) {
return false
}
return {
nodes,
edges,
}
}
/**
* 获取边的model
*/
getEdgeModelById(edgeId: string): BaseEdgeModel | undefined {
return this.edgesMap[edgeId]?.model
}
/**
* 获取节点或者边的model
*/
getElement(id: string): BaseNodeModel | BaseEdgeModel | undefined {
return this.modelsMap[id]
}
/**
* 所有节点上所有边的model
*/
getNodeEdges(nodeId: string): BaseEdgeModel[] {
const edges: BaseEdgeModel[] = []
for (let i = 0; i < this.edges.length; i++) {
const edgeModel = this.edges[i]
const nodeAsSource = edgeModel.sourceNodeId === nodeId
const nodeAsTarget = edgeModel.targetNodeId === nodeId
if (nodeAsSource || nodeAsTarget) {
edges.push(edgeModel)
}
}
return edges
}
/**
* 获取选中的元素数据
* @param isIgnoreCheck 是否包括sourceNode和targetNode没有被选中的边,默认包括。
* 复制的时候不能包括此类边, 因为复制的时候不允许悬空的边
*/
getSelectElements(isIgnoreCheck = true): GraphData {
const elements = this.selectElements
const graphData: GraphData = {
nodes: [],
edges: [],
}
elements.forEach((element) => {
if (element.BaseType === ElementType.NODE) {
graphData.nodes.push(element.getData())
}
if (element.BaseType === ElementType.EDGE) {
const edgeData = element.getData()
const isNodeSelected =
elements.get(edgeData.sourceNodeId) &&
elements.get(edgeData.targetNodeId)
if (isIgnoreCheck || isNodeSelected) {
graphData.edges.push(edgeData)
}
}
})
return graphData
}
/**
* 修改对应元素 model 中的属性
* 注意:此方法慎用,除非您对logicflow内部有足够的了解。
* 大多数情况下,请使用setProperties、updateText、changeNodeId等方法。
* 例如直接使用此方法修改节点的id,那么就是会导致连接到此节点的边的sourceNodeId出现找不到的情况。
* @param {string} id 元素id
* @param {object} attributes 需要更新的属性
*/
updateAttributes(id: string, attributes: object) {
const element = this.getElement(id)
element?.updateAttributes(attributes)
}
/**
* 修改节点的id, 如果不传新的id,会内部自动创建一个。
* @param { string } nodeId 将要被修改的id
* @param { string } newId 可选,修改后的id
* @returns 修改后的节点id, 如果传入的oldId不存在,返回空字符串
*/
changeNodeId(nodeId: string, newId?: string): string {
if (!newId) {
newId = createUuid()
}
if (this.nodesMap[newId]) {
console.warn(`当前流程图已存在节点${newId}, 修改失败`)
return ''
}
if (!this.nodesMap[nodeId]) {
console.warn(`当前流程图找不到节点${nodeId}, 修改失败`)
return ''
}
this.edges.forEach((edge) => {
if (edge.sourceNodeId === nodeId) {
edge.sourceNodeId = newId as string
}
if (edge.targetNodeId === nodeId) {
edge.targetNodeId = newId as string
}
})
this.nodesMap[nodeId].model.id = newId
this.nodesMap[newId] = this.nodesMap[nodeId]
return newId
}
/**
* 修改边的id, 如果不传新的id,会内部自动创建一个。
* @param { string } oldId 将要被修改的id
* @param { string } newId 可选,修改后的id
* @returns 修改后的节点id, 如果传入的oldId不存在,返回空字符串
*/
changeEdgeId<T extends string>(oldId: string, newId?: string): T | string {
if (!newId) {
newId = createUuid()
}
if (this.edgesMap[newId]) {
console.warn(`当前流程图已存在边: ${newId}, 修改失败`)
return ''
}
if (!this.edgesMap[oldId]) {
console.warn(`当前流程图找不到边: ${newId}, 修改失败`)
return ''
}
this.edges.forEach((edge) => {
if (edge.id === oldId) {
// edge.id = newId
edge.changeEdgeId(newId as string)
}
})
return newId
}
/**
* 获取元素的文本模式
* @param model
*/
getTextModel(model: BaseNodeModel): TextMode | undefined {
const { textMode, nodeTextMode, edgeTextMode } = this.editConfigModel
// textMode 的优先级:
// 元素自身 model.textMode > editConfigModel.node(edge)TextMode > editConfigModel.textMode
if (model.BaseType === ElementType.NODE) {
return model.textMode || nodeTextMode || textMode || TextMode.TEXT
}
// 同上
if (model.BaseType === ElementType.EDGE) {
return model.textMode || edgeTextMode || textMode || TextMode.TEXT
}
}
/**
* 更新元素的文本模式
* @param mode
* @param model
*/
@action
setTextMode(mode: TextMode, model?: BaseNodeModel | BaseEdgeModel) {
// 如果有传入 model,则直接更新 model 的 textMode
if (model) {
// model.updateTextMode(mode)
}
// 调用 editConfigModel 的方法更新 textMode
this.editConfigModel.updateEditConfig({ textMode: mode })
}
/**
* 内部保留方法,请勿直接使用
*/
@action
setFakeNode(nodeModel: BaseNodeModel) {
this.fakeNode = nodeModel
}
/**
* 内部保留方法,请勿直接使用
*/
@action
removeFakeNode() {
this.fakeNode = null
}
/**
* 设置指定类型的Model,请勿直接使用
*/
@action
setModel(type: string, ModelClass: LogicFlow.GraphElementCtor) {
return this.modelMap.set(type, ModelClass)
}
/**
* 将某个元素放置到顶部。
* 如果堆叠模式为默认模式,则将原置顶元素重新恢复原有层级。
* 如果堆叠模式为递增模式,则将需指定元素zIndex设置为当前最大zIndex + 1。
* @see todo link 堆叠模式
* @param id 元素Id
*/
@action
toFront(id: string) {
const element = this.nodesMap[id]?.model || this.edgesMap[id]?.model
if (element) {
if (this.overlapMode === OverlapMode.DEFAULT) {
this.topElement?.setZIndex()
element.setZIndex(ELEMENT_MAX_Z_INDEX)
this.topElement = element
}
if (this.overlapMode === OverlapMode.INCREASE) {
this.setElementZIndex(id, 'top')
}
}
}
/**
* 设置元素的zIndex.
* 注意:默认堆叠模式下,不建议使用此方法。
* @see todo link 堆叠模式
* @param id 元素id
* @param zIndex zIndex的值,可以传数字,也支持传入 'top' 和 'bottom'
*/
@action
setElementZIndex(id: string, zIndex: number | 'top' | 'bottom') {
const element = this.nodesMap[id]?.model || this.edgesMap[id]?.model
if (element) {
let index: number
if (typeof zIndex === 'number') {
index = zIndex
} else {
if (zIndex === 'top') {
index = getZIndex()
}
if (zIndex === 'bottom') {
index = getMinIndex()
}
}
element.setZIndex(index!)
}
}
/**
* 删除节点
* @param {string} nodeId 节点Id
*/
@action
deleteNode(nodeId: string) {
const nodeModel = this.nodesMap[nodeId].model
const nodeData = nodeModel.getData()
this.deleteEdgeBySource(nodeId)
this.deleteEdgeByTarget(nodeId)
this.nodes.splice(this.nodesMap[nodeId].index, 1)
this.eventCenter.emit(EventType.NODE_DELETE, {
data: nodeData,
model: nodeModel,
})
}
/**
* 添加节点
* @param nodeConfig 节点配置
* @param eventType 新增节点事件类型,默认EventType.NODE_ADD, 在Dnd拖拽时,会传入EventType.NODE_DND_ADD
* @param event MouseEvent 鼠标事件
*/
@action
addNode(
nodeConfig: NodeConfig,
eventType: EventType = EventType.NODE_ADD,
event?: MouseEvent,
) {
const originNodeData = formatData(nodeConfig)
// 添加节点的时候,如果这个节点 id 已经存在,则采用新 id
const { id } = originNodeData
if (id && this.nodesMap[id]) {
delete originNodeData.id
}
const nodeModel = this.getModelAfterSnapToGrid(originNodeData)
this.nodes.push(nodeModel)
const nodeData = nodeModel.getData()
const eventData: Record<string, any> = { data: nodeData }
if (event) {
eventData.e = event
}
this.eventCenter.emit(eventType, eventData)
return nodeModel
}
/**
* 将node节点位置进行grid修正
* 同时处理node内文字的偏移量
* 返回一个位置修正过的复制节点NodeModel
* @param node
*/
getModelAfterSnapToGrid(node: NodeConfig) {
const Model = this.getModel(node.type) as BaseNodeModelCtor
if (!Model) {
throw new Error(
`找不到${node.type}对应的节点,请确认是否已注册此类型节点。`,
)
}
const { x: nodeX, y: nodeY } = node
// 根据 grid 修正节点的 x, y
if (nodeX && nodeY) {
node.x = snapToGrid(nodeX, this.gridSize)
node.y = snapToGrid(nodeY, this.gridSize)
if (typeof node.text === 'object' && node.text !== null) {
// 原来的处理是:node.text.x -= getGridOffset(nodeX, this.gridSize)
// 由于snapToGrid()使用了Math.round()四舍五入的做法,因此无法判断需要执行
// node.text.x = node.text.x + getGridOffset()
// 还是
// node.text.x = node.text.x - getGridOffset()
// 直接改为node.x - nodeX就可以满足上面的要求
node.text.x += node.x - nodeX
node.text.y += node.y - nodeY
}
}
const nodeModel = new Model(node, this)
this.nodeModelMap.set(nodeModel.id, nodeModel)
this.elementsModelMap.set(nodeModel.id, nodeModel)
return nodeModel
}
/**
* 克隆节点
* @param nodeId 节点Id
*/
@action
cloneNode(nodeId: string) {
const targetNode = this.getNodeModelById(nodeId)
const data = targetNode?.getData()
if (data) {
data.x += 30
data.y += 30
data.id = ''
if (typeof data.text === 'object' && data.text !== null) {
data.text.x += 30
data.text.y += 30
}
const nodeModel = this.addNode(data)
nodeModel.setSelected(true)
targetNode?.setSelected(false)
return nodeModel.getData()
}
}
/**
* 移动节点-相对位置
* @param nodeId 节点Id
* @param deltaX X轴移动距离
* @param deltaY Y轴移动距离
* @param isIgnoreRule 是否忽略移动规则限制
*/
@action
moveNode(
nodeId: string,
deltaX: number,
deltaY: number,
isIgnoreRule = false,
) {
// 1) 移动节点
const node = this.nodesMap[nodeId]
if (!node) {
console.warn(`不存在id为${nodeId}的节点`)
return
}
const nodeModel = node.model
;[deltaX, deltaY] = nodeModel.getMoveDistance(deltaX, deltaY, isIgnoreRule)
// 2) 移动边
this.moveEdge(nodeId, deltaX, deltaY)
}
/**
* 移动节点-绝对位置
* @param nodeId 节点Id
* @param x X轴目标位置
* @param y Y轴目标位置
* @param isIgnoreRule 是否忽略条件,默认为 false
*/
@action
moveNode2Coordinate(
nodeId: string,
x: number,
y: number,
isIgnoreRule = false,
) {
// 1) 移动节点
const node = this.nodesMap[nodeId]
if (!node) {
console.warn(`不存在id为${nodeId}的节点`)
return
}
const nodeModel = node.model
const { x: originX, y: originY } = nodeModel
const deltaX = x - originX
const deltaY = y - originY
this.moveNode(nodeId, deltaX, deltaY, isIgnoreRule)
}
/**
* 显示节点、连线文本编辑框
* @param id 节点 or 连线 id
*/
@action
editText(id: string) {
this.setElementStateById(id, ElementState.TEXT_EDIT)
}
/**
* 给两个节点之间添加一条边
* @param {object} edgeConfig
*/
@action
addEdge(edgeConfig: LogicFlow.EdgeConfig): BaseEdgeModel {
const edgeOriginData = formatData(edgeConfig)
// 边的类型优先级:自定义>全局>默认
let { type } = edgeOriginData
if (!type) {
type = this.edgeType
}