-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathLogicFlow.tsx
More file actions
2044 lines (1866 loc) · 56.2 KB
/
LogicFlow.tsx
File metadata and controls
2044 lines (1866 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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 { ComponentType, createElement as h, render } from 'preact/compat'
import { cloneDeep, forEach, indexOf, isEqual, isNil } from 'lodash-es'
import { observer } from '.'
import { Options as LFOptions } from './options'
import * as _Model from './model'
import {
BaseEdgeModel,
BaseNodeModel,
IEditConfigType,
GraphModel,
SnaplineModel,
ZoomParamType,
} from './model'
import Graph from './view/Graph'
import * as _View from './view'
import {
formatData,
addThemeMode,
removeThemeMode,
clearThemeMode,
} from './util'
import { Dnd, snapline } from './view/behavior'
import Tool from './tool'
import History from './history'
import Keyboard, { initDefaultShortcut } from './keyboard'
import { EventCallback, CallbackArgs, EventArgs } from './event/eventEmitter'
import {
ElementType,
EventType,
OverlapMode,
SegmentDirection,
} from './constant'
import { Grid } from './view/overlay'
import Extension = LogicFlow.Extension
import ExtensionConfig = LogicFlow.ExtensionConfig
import ExtensionConstructor = LogicFlow.ExtensionConstructor
import GraphConfigData = LogicFlow.GraphConfigData
import NodeConfig = LogicFlow.NodeConfig
import EdgeConfig = LogicFlow.EdgeConfig
import GraphData = LogicFlow.GraphData
import NodeData = LogicFlow.NodeData
import EdgeData = LogicFlow.EdgeData
import RegisterConfig = LogicFlow.RegisterConfig
import RegisterParam = LogicFlow.RegisterParam
import GraphElements = LogicFlow.GraphElements
import Position = LogicFlow.Position
import PointTuple = LogicFlow.PointTuple
import ExtensionRenderFunc = LogicFlow.ExtensionRenderFunc
import RegisterElementFunc = LogicFlow.RegisterElementFunc
import PropertiesType = LogicFlow.PropertiesType
import BaseNodeModelCtor = LogicFlow.BaseNodeModelCtor
import ClientPosition = LogicFlow.ClientPosition
import ExtensionDefinition = LogicFlow.ExtensionDefinition
import ExtensionType = LogicFlow.ExtensionType
const pluginFlag = Symbol('plugin registered by Logicflow.use')
export class LogicFlow {
// 只读:logicflow实例挂载的容器。
readonly container: HTMLElement
// 只读:logicflow实例的配置
readonly options: LFOptions.Definition
// 只读:控制整个 LogicFlow 画布的model
readonly graphModel: GraphModel
viewMap: Map<string, ComponentType> = new Map()
history: History
keyboard: Keyboard
dnd: Dnd
tool: Tool
snaplineModel?: SnaplineModel
components: ExtensionRenderFunc[] = []
// 个性配置的插件,覆盖全局配置的插件
readonly plugins: ExtensionType[]
// 全局配置的插件,所有的LogicFlow示例都会使用
static extensions: Map<string, ExtensionConfig> = new Map()
// 插件扩展方法
extension: Record<string, Extension | ExtensionDefinition> = {}
readonly width?: number // 只读:画布宽度
readonly height?: number // 只读:画布高度
/**
* 自定义数据转换方法
* 当接入系统格式和 LogicFlow 数据格式不一致时,可自定义此方法来进行数据格式转换
* 详情请参考 adapter docs
* 包括 adapterIn 和 adapterOut 两个方法
*/
// TODO: 如何让用户执行时定义下面方法参数和返回值的类型
adapterIn?: (data: unknown) => GraphData
adapterOut?: (data: GraphData, ...rest: any) => unknown;
// 支持插件在 LogicFlow 实例上增加自定义方法
[propName: string]: any
private initContainer(
container: HTMLElement | HTMLDivElement,
width?: number,
height?: number,
) {
// TODO: 确认是否需要,后续是否只要返回 container 即可(下面方法是为了解决事件绑定问题的)
// fix: destroy keyboard events while destroy LogicFlow.(#1110)
const lfContainer = document.createElement('div')
lfContainer.style.position = 'relative'
lfContainer.style.width = width ? `${width}px` : '100%'
lfContainer.style.height = height ? `${height}px` : '100%'
container.innerHTML = ''
container.appendChild(lfContainer)
return lfContainer
}
protected get [Symbol.toStringTag]() {
return LogicFlow.toStringTag
}
constructor(options: LFOptions.Common) {
const initOptions = LFOptions.get(options)
const { container, width, height } = initOptions
this.options = initOptions
this.container = this.initContainer(container, width, height)
this.graphModel = new GraphModel({
...initOptions,
container: this.container, // TODO:测试该部分是否会有问题
})
this.plugins = initOptions.plugins ?? []
const { eventCenter } = this.graphModel
this.tool = new Tool(this)
this.dnd = new Dnd({ lf: this })
this.history = new History(eventCenter)
this.keyboard = new Keyboard({
lf: this,
keyboard: initOptions.keyboard,
})
if (initOptions.snapline !== false) {
this.snaplineModel = new SnaplineModel(
this.graphModel,
initOptions.snaplineEpsilon,
)
snapline(eventCenter, this.snaplineModel)
}
if (!initOptions.isSilentMode) {
// 先初始化默认内置快捷键,自定义快捷键可以覆盖默认快捷键
initDefaultShortcut(this, this.graphModel)
// 然后再初始化自定义快捷键,自定义快捷键可以覆盖默认快捷键.
// 插件最后初始化。方便插件强制覆盖内置快捷键
this.keyboard.initShortcuts()
}
this.defaultRegister()
this.installPlugins(initOptions.disabledPlugins)
}
/*********************************************************
* Register 相关
********************************************************/
private setView = (type: string, component: ComponentType) =>
this.viewMap.set(type, component)
// 根据 type 获取对应的 view
private getView = (type: string): ComponentType | undefined =>
this.viewMap.get(type)
// register 方法重载
register(element: RegisterConfig): void
register(
type: string,
fn: RegisterElementFunc,
isObserverView?: boolean,
): void
/**
* 注册自定义节点和边
* 支持两种方式
* 方式一(推荐)
* 详情见 todo: docs link
* @example
* import { RectNode, RectModel } from '@logicflow/core'
* class CustomView extends RectNode {
* }
* class CustomModel extends RectModel {
* }
* lf.register({
* type: 'custom',
* view: CustomView,
* model: CustomModel
* })
* 方式二
* 不推荐,极个别在自定义的时候需要用到lf的情况下可以用这种方式。
* 大多数情况下,我们可以直接在view中从this.props中获取graphModel
* 或者model中直接this.graphModel获取model的方法。
* @example
* lf.register('custom', ({ RectNode, RectModel }) => {
* class CustomView extends RectNode {}
* class CustomModel extends RectModel {}
* return {
* view: CustomView,
* model: CustomModel
* }
* })
*/
register(
element: string | RegisterConfig,
fn?: RegisterElementFunc,
isObserverView = true,
) {
// 方式1
if (typeof element !== 'string') {
this.registerElement(element)
return
}
// 方式2 TODO: 优化下面这段代码,没太看懂这一块的背景
const registerParam: RegisterParam = {
BaseEdge: _View.BaseEdge,
BaseEdgeModel: _Model.BaseEdgeModel,
BaseNode: _View.BaseNode,
BaseNodeModel: _Model.BaseNodeModel,
RectNode: _View.RectNode,
RectNodeModel: _Model.RectNodeModel,
CircleNode: _View.CircleNode,
CircleNodeModel: _Model.CircleNodeModel,
PolygonNode: _View.PolygonNode,
PolygonNodeModel: _Model.PolygonNodeModel,
TextNode: _View.TextNode,
TextNodeModel: _Model.TextNodeModel,
LineEdge: _View.LineEdge,
LineEdgeModel: _Model.LineEdgeModel,
DiamondNode: _View.DiamondNode,
DiamondNodeModel: _Model.DiamondNodeModel,
PolylineEdge: _View.PolylineEdge,
PolylineEdgeModel: _Model.PolylineEdgeModel,
BezierEdge: _View.BezierEdge,
BezierEdgeModel: _Model.BezierEdgeModel,
EllipseNode: _View.EllipseNode,
EllipseNodeModel: _Model.EllipseNodeModel,
HtmlNode: _View.HtmlNode,
HtmlNodeModel: _Model.HtmlNodeModel,
// mobx,
h,
type: element,
}
// 为了能让后来注册的可以继承前面注册的
// 例如我注册一个“开始节点”
// 然后我再想注册一个“立即开始节点”
// 注册传递参数改为动态。
// TODO: 确定 extendKey 的作用
this.viewMap.forEach((component) => {
const key = (component as any).extendKey
if (key) {
registerParam[key] = component
}
})
this.graphModel.modelMap.forEach((component) => {
const key = (component as any).extendKey
if (key) {
registerParam[key as string] = component
}
})
if (fn) {
const { view: ViewClass, model: ModelClass } = fn(registerParam)
let vClass = ViewClass as any // TODO: 确认 ViewClass 类型
if (isObserverView && !vClass.isObserved) {
vClass.isObserved = true
vClass = observer(vClass)
}
this.setView(element, vClass)
this.graphModel.setModel(element, ModelClass)
}
}
/**
* 注册元素(节点 or 边)
* @param config 注册元素的配置项
* @private
*/
private registerElement(config: RegisterConfig) {
let ViewComp = config.view
if (config.isObserverView !== false && !ViewComp.isObserved) {
ViewComp.isObserved = true
ViewComp = observer(ViewComp)
}
this.setView(config.type, ViewComp)
this.graphModel.setModel(config.type, config.model)
}
/**
* 批量注册元素
* @param elements 注册的元素
*/
batchRegister(elements: RegisterConfig[] = []) {
forEach(elements, (element) => {
this.registerElement(element)
})
}
private defaultRegister() {
// LogicFlow default Nodes and Edges
const defaultElements: RegisterConfig[] = [
// Node
{
type: 'rect',
view: _View.RectNode,
model: _Model.RectNodeModel,
},
{
type: 'circle',
view: _View.CircleNode,
model: _Model.CircleNodeModel,
},
{
type: 'polygon',
view: _View.PolygonNode,
model: _Model.PolygonNodeModel,
},
{
type: 'text',
view: _View.TextNode,
model: _Model.TextNodeModel,
},
{
type: 'ellipse',
view: _View.EllipseNode,
model: _Model.EllipseNodeModel,
},
{
type: 'diamond',
view: _View.DiamondNode,
model: _Model.DiamondNodeModel,
},
{
type: 'html',
view: _View.HtmlNode,
model: _Model.HtmlNodeModel,
},
// Edge
{
type: 'line',
view: _View.LineEdge,
model: _Model.LineEdgeModel,
},
{
type: 'polyline',
view: _View.PolylineEdge,
model: _Model.PolylineEdgeModel,
},
{
type: 'bezier',
view: _View.BezierEdge,
model: _Model.BezierEdgeModel,
},
]
this.batchRegister(defaultElements)
}
/*********************************************************
* Node 相关方法
********************************************************/
/**
* 添加节点
* @param nodeConfig 节点配置
* @param eventType 新增节点事件类型,默认EventType.NODE_ADD
* @param e MouseEvent 事件
*/
addNode(
nodeConfig: NodeConfig,
eventType: EventType = EventType.NODE_ADD,
e?: MouseEvent,
): BaseNodeModel {
return this.graphModel.addNode(nodeConfig, eventType, e)
}
/**
* 删除节点
* @param {string} nodeId 节点Id
*/
deleteNode(nodeId: string): boolean {
const nodeModel = this.graphModel.getNodeModelById(nodeId)
if (!nodeModel) return false
const nodeData = nodeModel.getData()
const { guards } = this.options
const isEnableDelete = guards?.beforeDelete
? guards.beforeDelete(nodeData)
: true
if (isEnableDelete) {
this.graphModel.deleteNode(nodeId)
}
return isEnableDelete
}
/**
* 克隆节点
* @param nodeId 节点Id
*/
cloneNode(nodeId: string): NodeData | undefined {
const nodeModel = this.graphModel.getNodeModelById(nodeId)
const nodeData = nodeModel?.getData()
if (nodeData) {
const { guards } = this.options
const isEnableClone = guards?.beforeClone
? guards.beforeClone(nodeData)
: true
if (isEnableClone) {
return this.graphModel.cloneNode(nodeId)
}
}
}
/**
* 修改节点的id,如果不传新的id,会内部自动创建一个。
* @param { string } nodeId 将要被修改的id
* @param { string } newId 可选,修改后的id
* @returns 修改后的节点id, 如果传入的oldId不存在,返回空字符串
*/
changeNodeId(nodeId: string, newId?: string): string {
return this.graphModel.changeNodeId(nodeId, newId)
}
/**
* 修改指定节点类型
* @param nodeId 节点id
* @param type 节点类型
*/
changeNodeType(nodeId: string, type: string): void {
this.graphModel.changeNodeType(nodeId, type)
}
/**
* 获取节点对象
* @param nodeId 节点Id
*/
getNodeModelById(nodeId: string): BaseNodeModel | undefined {
return this.graphModel.getNodeModelById(nodeId)
}
/**
* 获取节点数据
* @param nodeId 节点
*/
getNodeDataById(nodeId: string): NodeData | undefined {
const nodeModel = this.getNodeModelById(nodeId)
return nodeModel?.getData()
}
/**
* 获取所有以此节点为终点的边
* @param { string } nodeId
*/
getNodeIncomingEdge(nodeId: string) {
return this.graphModel.getNodeIncomingEdge(nodeId)
}
/**
* 获取所有以此节点为起点的边
* @param {string} nodeId
*/
getNodeOutgoingEdge(nodeId: string) {
return this.graphModel.getNodeOutgoingEdge(nodeId)
}
/**
* 获取节点连接到的所有起始节点
* @param {string} nodeId
*/
getNodeIncomingNode(nodeId: string) {
return this.graphModel.getNodeIncomingNode(nodeId)
}
/**
* 获取节点连接到的所有目标节点
* @param {string} nodeId
*/
getNodeOutgoingNode(nodeId: string) {
return this.graphModel.getNodeOutgoingNode(nodeId)
}
/**
* 内部保留方法
* 创建一个fakeNode,用于dnd插件拖动节点进画布的时候使用。
*/
createFakeNode(nodeConfig: NodeConfig) {
const Model = this.graphModel.modelMap.get(
nodeConfig.type,
) as BaseNodeModelCtor
if (!Model) {
console.warn(`不存在为${nodeConfig.type}类型的节点`)
return null
}
// * initNodeData区分是否为虚拟节点
const fakeNodeModel = new Model(
{
...nodeConfig,
virtual: true,
},
this.graphModel,
)
this.graphModel.setFakeNode(fakeNodeModel)
return fakeNodeModel
}
/**
* 内部保留方法
* 移除fakeNode
*/
removeFakeNode() {
this.graphModel.removeFakeNode()
}
/**
* 内部保留方法
* 用于fakeNode显示对齐线
*/
setNodeSnapLine(data: NodeData) {
this.snaplineModel?.setNodeSnapLine(data)
}
/**
* 内部保留方法
* 用于fakeNode移除对齐线
*/
removeNodeSnapLine() {
this.snaplineModel?.clearSnapline()
}
/*********************************************************
* Edge 相关方法
********************************************************/
/**
* 设置默认的边类型。
* 也就是设置在节点直接由用户手动绘制的连线类型。
* @param type LFOptions.EdgeType
*/
setDefaultEdgeType(type: LFOptions.EdgeType): void {
this.graphModel.setDefaultEdgeType(type)
}
/**
* 给两个节点之间添加一条边
* @example
* lf.addEdge({
* type: 'polygon'
* sourceNodeId: 'node_id_1',
* targetNodeId: 'node_id_2',
* })
* @param {EdgeConfig} edgeConfig
*/
addEdge(edgeConfig: EdgeConfig): BaseEdgeModel {
return this.graphModel.addEdge(edgeConfig)
}
/**
* 基于id获取边数据
* @param edgeId 边Id
* @returns EdgeData
*/
getEdgeDataById(edgeId: string): EdgeData | undefined {
const edgeModel = this.getEdgeModelById(edgeId)
return edgeModel?.getData()
}
/**
* 基于边Id获取边的model
* @param edgeId 边的Id
* @return model
*/
getEdgeModelById(edgeId: string): BaseEdgeModel | undefined {
return this.graphModel.getEdgeModelById(edgeId)
}
/**
* 获取满足条件边的model
* @param edgeFilter 过滤条件
* @example
* 获取所有起点为节点 A 的边的 model
* lf.getEdgeModels({
* sourceNodeId: 'nodeA_id'
* })
* 获取所有终点为节点 B 的边的 model
* lf.getEdgeModels({
* targetNodeId: 'nodeB_id'
* })
* 获取起点为节点 A,终点为节点 B 的边
* lf.getEdgeModels({
* sourceNodeId: 'nodeA_id',
* targetNodeId: 'nodeB_id'
* })
* @return model数组
*/
getEdgeModels({
sourceNodeId,
targetNodeId,
}: {
sourceNodeId?: string
targetNodeId?: string
}): BaseEdgeModel[] {
const results: BaseEdgeModel[] = []
const { edges } = this.graphModel
if (sourceNodeId && targetNodeId) {
forEach(edges, (edge) => {
if (
edge.sourceNodeId === sourceNodeId &&
edge.targetNodeId === targetNodeId
) {
results.push(edge)
}
})
} else if (sourceNodeId) {
forEach(edges, (edge) => {
if (edge.sourceNodeId === sourceNodeId) {
results.push(edge)
}
})
} else if (targetNodeId) {
forEach(edges, (edge) => {
if (edge.targetNodeId === targetNodeId) {
results.push(edge)
}
})
}
return results
}
/**
* 修改边的id, 如果不传新的id,会内部自动创建一个。
* @param { string } edgeId 将要被修改的id
* @param { string } newId 可选,修改后的id
* @returns 修改后的节点id, 如果传入的oldId不存在,返回空字符串
*/
changeEdgeId(edgeId: string, newId?: string): string {
return this.graphModel.changeEdgeId(edgeId, newId)
}
/**
* 切换边的类型
* @param edgeId 边Id
* @param type 边类型
*/
changeEdgeType(edgeId: string, type: LFOptions.EdgeType): void {
this.graphModel.changeEdgeType(edgeId, type)
}
/**
* 删除边
* @param {string} edgeId 边Id
*/
deleteEdge(edgeId: string): boolean {
const edgeModel = this.graphModel.getEdgeModelById(edgeId)
if (!edgeModel) return false
const edgeData = edgeModel.getData()
const { guards } = this.options
const isEnableDelete = guards?.beforeDelete
? guards.beforeDelete(edgeData)
: true
if (isEnableDelete) {
this.graphModel.deleteEdgeById(edgeId)
}
return isEnableDelete
}
/**
* 基于给定节点(作为边起点或终点,可以只传其一),删除对应的边
* @param sourceNodeId 边的起点节点ID
* @param targetNodeId 边的终点节点ID
*/
deleteEdgeByNodeId({
sourceNodeId,
targetNodeId,
}: {
sourceNodeId?: string
targetNodeId?: string
}): void {
// TODO: 将下面方法从 this.graphModel 解构,并测试代码功能是否正常(需要确认 this 指向是否有异常)
if (sourceNodeId && targetNodeId) {
this.graphModel.deleteEdgeBySourceAndTarget(sourceNodeId, targetNodeId)
} else if (sourceNodeId) {
this.graphModel.deleteEdgeBySource(sourceNodeId)
} else if (targetNodeId) {
this.graphModel.deleteEdgeByTarget(targetNodeId)
}
}
/**
* 获取节点连接的所有边的model
* @param nodeId 节点ID
* @returns model数组
*/
getNodeEdges(nodeId: string): BaseEdgeModel[] {
return this.graphModel.getNodeEdges(nodeId)
}
/*********************************************************
* Element 相关方法
********************************************************/
/**
* 添加多个元素, 包括边和节点。
* @param nodes
* @param edges
* @param distance
*/
addElements({ nodes, edges }: GraphConfigData, distance = 40): GraphElements {
// TODO: 1. 解决下面方法中 distance 传参缺未使用的问题;该方法在快捷键中有调用
// TODO: 2. review 一下本函数代码逻辑,确认 nodeIdMap 的作用,看是否有优化的空间
console.log('distance', distance)
const nodeIdMap: Record<string, string> = {}
const elements: GraphElements = {
nodes: [],
edges: [],
}
forEach(nodes, (node) => {
const nodeId = node.id
const nodeModel = this.addNode(node)
if (nodeId) nodeIdMap[nodeId] = nodeModel.id
elements.nodes.push(nodeModel)
})
forEach(edges, (edge) => {
let { sourceNodeId, targetNodeId } = edge
if (nodeIdMap[sourceNodeId]) sourceNodeId = nodeIdMap[sourceNodeId]
if (nodeIdMap[targetNodeId]) targetNodeId = nodeIdMap[targetNodeId]
const edgeModel = this.graphModel.addEdge({
...edge,
sourceNodeId,
targetNodeId,
})
elements.edges.push(edgeModel)
})
return elements
}
/**
* 将图形选中
* @param id 选择元素ID
* @param multiple 是否允许多选,如果为true,不会将上一个选中的元素重置
* @param toFront 是否将选中的元素置顶,默认为true
*/
selectElementById(id: string, multiple = false, toFront = true) {
this.graphModel.selectElementById(id, multiple)
if (!multiple && toFront) {
this.graphModel.toFront(id)
}
}
/**
* 移除选中的元素
* @param id 元素ID
*/
deselectElementById(id: string) {
this.graphModel.deselectElementById(id)
}
/**
* 获取选中的元素数据
* @param isIgnoreCheck 是否包括sourceNode和targetNode没有被选中的边,默认包括。
* 注意:复制的时候不能包括此类边, 因为复制的时候不允许悬空的边。
*/
getSelectElements(isIgnoreCheck = true): GraphData {
return this.graphModel.getSelectElements(isIgnoreCheck)
}
/**
* 将所有选中的元素设置为非选中
*/
clearSelectElements() {
this.graphModel.clearSelectElements()
}
/**
* 获取节点或边对象
* @param id id
*/
getModelById(id: string): LogicFlow.GraphElement | undefined {
return this.graphModel.getElement(id)
}
/**
* 获取节点或边的数据
* @param id id
*/
getDataById(id: string): NodeData | EdgeData | undefined {
return this.graphModel.getElement(id)?.getData()
}
/**
* 删除元素,在不确定当前id是节点还是边时使用
* @param id 元素id
*/
deleteElement(id: string): boolean {
const model = this.getModelById(id)
if (!model) return false
const callback = {
[ElementType.NODE]: this.deleteNode,
[ElementType.EDGE]: this.deleteEdge,
}
return callback[model.BaseType]?.call(this, id) ?? false
}
/**
* 设置元素的zIndex.
* 注意:默认堆叠模式下,不建议使用此方法。
* @see todo link 堆叠模式
* @param id 元素id
* @param zIndex zIndex的值,可以传数字,也支持传入 'top' 和 'bottom'
*/
setElementZIndex(id: string, zIndex: number | 'top' | 'bottom') {
return this.graphModel.setElementZIndex(id, zIndex)
}
/**
* 获取指定区域内的所有元素,此区域必须是DOM层。
* 例如鼠标绘制选区后,获取选区内的所有元素。
* @see todo 分层
* @param leftTopPoint 区域左上角坐标, dom层坐标
* @param rightBottomPoint 区域右下角坐标,dom层坐标
* @param wholeEdge
* @param wholeNode
* @param ignoreHideElement
*/
getAreaElement(
leftTopPoint: PointTuple,
rightBottomPoint: PointTuple,
wholeEdge = true,
wholeNode = true,
ignoreHideElement = false,
) {
return this.graphModel
.getAreaElement(
leftTopPoint,
rightBottomPoint,
wholeEdge,
wholeNode,
ignoreHideElement,
)
.map((element) => element.getData())
}
/**
* 设置元素的自定义属性
* @see http://logicflow.cn/api/detail#setproperties
* @param id 元素的id
* @param properties 自定义属性
*/
setProperties(id: string, properties: PropertiesType): void {
this.graphModel.getElement(id)?.setProperties(formatData(properties))
}
/**
* 获取元素的自定义属性
* @param id 元素的id
* @returns 自定义属性
*/
getProperties(id: string): PropertiesType | undefined {
return this.graphModel.getElement(id)?.getProperties()
}
deleteProperty(id: string, key: string): void {
this.graphModel.getElement(id)?.deleteProperty(key)
}
/**
* FBI WARNING !!! 慎用 === 不要用
* 修改对应元素 model 中的属性
* 注意:此方法慎用,除非您对logicflow内部有足够的了解。
* 大多数情况下,请使用setProperties、updateText、changeNodeId等方法。
* 例如直接使用此方法修改节点的id,那么就是会导致连接到此节点的边的sourceNodeId出现找不到的情况。
* @param {string} id 元素id
* @param {object} attributes 需要更新的属性
*/
updateAttributes(id: string, attributes: object) {
this.graphModel.updateAttributes(id, attributes)
}
/*********************************************************
* Text 相关方法
********************************************************/
/**
* 显示节点、连线文本编辑框
* @param id 元素id
*/
editText(id: string): void {
this.graphModel.editText(id)
}
/**
* 更新节点或边的文案
* @param id 节点或者边id
* @param value 文案内容
*/
updateText(id: string, value: string) {
this.graphModel.updateText(id, value)
}
/*********************************************************
* EditConfig 相关方法
********************************************************/
/**
* 更新流程图编辑相关设置
* @param {object} config 编辑配置
* @see http://logicflow.cn/api/detail#updateeditconfig
*/
updateEditConfig(config: Partial<IEditConfigType>) {
const { editConfigModel, transformModel } = this.graphModel
const currentSnapGrid = editConfigModel.snapGrid
editConfigModel.updateEditConfig(config)
if (config?.stopMoveGraph !== undefined) {
transformModel.updateTranslateLimits(config.stopMoveGraph)
}
// 静默模式切换时,修改快捷键的启用状态
config?.isSilentMode ? this.keyboard.disable() : this.keyboard.enable(true)
// 切换网格对齐状态时,修改网格尺寸
if (!isNil(config?.snapGrid) && config.snapGrid !== currentSnapGrid) {
const {
grid: { size = 1 },
} = this.graphModel
this.graphModel.updateGridSize(config.snapGrid ? size : 1)
}
this.emit(EventType.EDIT_CONFIG_CHANGED, {
data: editConfigModel.getConfig(),
})
}
/**
* 获取流程图当前编辑相关设置
* @see http://logicflow.cn/api/detail#geteditconfig
*/
getEditConfig() {
return this.graphModel.editConfigModel.getConfig()
}
/*********************************************************
* Graph 相关方法
********************************************************/
/**
* 设置主题样式
* @param { object } style 自定义主题样式
* todo docs link
*/
setTheme(
style: Partial<LogicFlow.Theme>,
themeMode?: 'radius' | 'dark' | 'colorful' | 'default' | string,
): void {
this.graphModel.setTheme(style, themeMode)
}
/**
* 获取当前主题样式
* @see todo docs link
*/
getTheme(): LogicFlow.Theme {
return this.graphModel.getTheme()
}
private focusByElement(id: string) {
let coordinate: Position | undefined = undefined
const nodeModel = this.getNodeModelById(id)
if (nodeModel) {
const { x, y } = nodeModel.getData()
coordinate = {
x,
y,
}
}
const edgeModel = this.getEdgeModelById(id)
if (edgeModel) {
const { x, y } = edgeModel.textPosition
coordinate = {
x,
y,
}
}
if (coordinate) {
this.focusByCoordinate(coordinate)
}
}
private focusByCoordinate(coordinate: Position) {
const { transformModel, width, height } = this.graphModel
const { x, y } = coordinate
transformModel.focusOn(x, y, width, height)
}
/**
* 定位到画布视口中心
* 支持用户传入图形当前的坐标或id,可以通过type来区分是节点还是边的id,也可以不传(兜底)
* @param focusOnArgs.id 如果传入的是id, 则画布视口中心移动到此id的元素中心点。
* @param focusOnArgs.coordinate 如果传入的是坐标,则画布视口中心移动到此坐标。
* TODO: 测试下面代码,重构了一下逻辑,重载 api 定义
*/
focusOn(id: string): void
focusOn(coordinate: Position): void
focusOn(focusOnArgs: LogicFlow.FocusOnArgsType): void