forked from syncfusion/blazor-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextToMindMap.razor
More file actions
1177 lines (1128 loc) · 55.8 KB
/
TextToMindMap.razor
File metadata and controls
1177 lines (1128 loc) · 55.8 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
@page "/ai-diagram/text-to-mindmap"
@using Syncfusion.Blazor.Diagram
@using Syncfusion.Blazor.Buttons
@using Syncfusion.Blazor.Inputs
@using Syncfusion.Blazor.Popups
@using Syncfusion.Blazor.Spinner
@using System.Collections.ObjectModel
@using Syncfusion.Blazor.Diagram.SymbolPalette
@using System.Text.Json;
@using Syncfusion.Blazor.Navigations
@using DiagramShapes = Syncfusion.Blazor.Diagram.NodeShapes
@using DiagramSegments = Syncfusion.Blazor.Diagram.ConnectorSegment
@using Orientation= Syncfusion.Blazor.Diagram.Orientation
@using Shapes = Syncfusion.Blazor.Diagram.NodeShapes
@using BlazorDemos.Service
@inject AzureAIService ChatGptService
@namespace TextToMindMapDiagram
@inject IJSRuntime JS
@*Hidden:Lines*@
@inherits SampleBaseComponent
@inject NavigationManager NavigationManager
@*End:Hidden*@
<SampleDescription>
<p>
This demo sample showcases the creation of a dynamic mindmap diagram using the Blazor Diagram Component with the assistance of AI. The AI-powered diagram features nodes and connectors arranged in a mindmap layout, designed to visually organize and represent ideas and concepts. This sample is ideal for brainstorming, organizing thoughts, and visually mapping out complex information. The context menu allows for quick actions such as adding, editing, or deleting nodes, making it a powerful tool for interactively managing and expanding mindmaps.
</p>
<p>
Explore our <strong>Smart AI demos</strong> with limited AI token usage directly in your browser. To dive deeper and try out these features locally using your own API key, check out our
<a href="https://github.com/syncfusion/smart-ai-samples/tree/master/blazor" target="_blank" aria-label="Navigate to the Syncfusion Smart AI Samples GitHub repository">
<strong>Syncfusion Smart AI Samples</strong>
</a> on GitHub.
</p>
</SampleDescription>
<ActionDescription>
<p>
This sample leverages a specialized AI prompt, allowing users to generate the content of the diagram by submitting a prompt to OpenAI. The AI's response is parsed and transformed into nodes and connectors, visually representing the generated ideas or concepts in a mindmap format. Users can also manually add child nodes using user handles to further expand and customize the mindmap, creating an interactive and personalized experience.
</p>
</ActionDescription>
@*Hidden:Lines*@
<AINotification></AINotification>
@*End:Hidden*@
@*Hidden:Lines*@
<AIToastNotification></AIToastNotification>
@*End:Hidden*@
<div class="col-lg-12 control-section">
<div class="content-wrapper">
<div class="diagrambuilder-container" style="height: calc(100% - 350px); width: 100%">
<div style="border: 2px solid #ccc;">
<DiagramMenuBar @ref="@MenubarRef"></DiagramMenuBar>
<DiagramToolBar @ref="@Toolbar"></DiagramToolBar>
<div class="diagram-area">
<SfDiagramComponent ID="diagram-area" @ref="@Diagram" @bind-InteractionController="@interactionController" @bind-Nodes="@nodes" @bind-Connectors="@connectors" ScrollChanged="ScrollChanged" CollectionChanging="CollectionChanging" @bind-Height="@height" @bind-Width="@width" GetCustomTool="@GetCustomTool" NodeCreating="@NodeCreating" ConnectorCreating="@ConnectorCreating" @bind-SelectionSettings="@selectionSettings" SelectionChanging="OnSelectionChanging" Created="OnCreated" SelectionChanged="@SelectionChanged" HistoryChanged="@HistoryChange">
<ScrollSettings @bind-ScrollLimit="@scrollLimit" @bind-CurrentZoom="@CurrentZoom" @bind-MaxZoom="@maxZoom" @bind-MinZoom="@minZoom"></ScrollSettings>
<Layout @bind-HorizontalSpacing="@HorizontalSpacing" @bind-VerticalSpacing="@VerticalSpacing" @bind-Type="@layoutType" GetBranch="@getbranch"></Layout>
<SnapSettings @bind-Constraints="@SnapConstraint"></SnapSettings>
<PageSettings MultiplePage="true"></PageSettings>
<CommandManager @bind-Commands="@commands" Execute="@ExecuteCommand" CanExecute="@CanExecute" />
<SfSpinner @ref="@SpinnerRef" Label="Generating diagram...." Type="@SpinnerType.Bootstrap"> </SfSpinner>
</SfDiagramComponent>
</div>
</div>
<DiagramShortCutKey @ref="@DiagramShortCutKeyRef"></DiagramShortCutKey>
<DiagramOpenAI @ref="DiagramOpenAIRef"></DiagramOpenAI>
</div>
</div>
</div>
@code{
public SfDiagramComponent Diagram;
public SfSpinner SpinnerRef;
public DiagramOpenAI DiagramOpenAIRef;
public DiagramShortCutKey DiagramShortCutKeyRef;
public DiagramMenuBar MenubarRef;
public DiagramToolBar Toolbar;
public SnapConstraints SnapConstraint = SnapConstraints.ShowLines;
public double CurrentZoom { get; set; } = 1;
public bool IsGeneratingFromAI = false;
/// <summary>
/// Collection of keyboard commands for the diagram.
/// </summary>
DiagramObjectCollection<KeyboardCommand> commands = new DiagramObjectCollection<KeyboardCommand>();
/// <summary>
/// The minimum zoom level allowed for the diagram.
/// </summary>
private double minZoom { get; set; } = 0.25;
/// <summary>
/// The maximum zoom level allowed for the diagram.
/// </summary>
private double maxZoom { get; set; } = 30;
/// <summary>
/// Specifies whether the undo functionality is enabled in the diagram.
/// </summary>
public bool IsUndo = false;
/// <summary>
/// Specifies whether the redo functionality is enabled in the diagram.
/// </summary>
public bool IsRedo = false;
/// <summary>
/// Specifies whether the diagram is selected.
/// </summary>
public bool diagramSelected = false;
/// <summary>
/// Represents an array of fill colors.
/// </summary>
private static string[] fillColorCode = { "#C4F2E8", "#F7E0B3", "#E5FEE4", "#E9D4F1", "#D4EFED", "#DEE2FF" };
/// <summary>
/// Represents an array of border colors.
/// </summary>
private static string[] borderColorCode = { "#8BC1B7", "#E2C180", "#ACCBAA", "#D1AFDF", "#90C8C2", "#BBBFD6" };
/// <summary>
/// Represents the last fill index, an integer.
/// </summary>
private static int lastFillIndex = 0;
LayoutType layoutType = LayoutType.MindMap;
public string height = "700px";
public string width = "100%";
public DiagramObjectCollection<Node> nodes = new DiagramObjectCollection<Node>();
public DiagramObjectCollection<Connector> connectors = new DiagramObjectCollection<Connector>();
ScrollLimitMode scrollLimit { get; set; } = ScrollLimitMode.Diagram;
DiagramInteractions interactionController = DiagramInteractions.SingleSelect;
int VerticalSpacing = 20;
int HorizontalSpacing = 80;
DiagramSelectionSettings selectionSettings = new DiagramSelectionSettings();
DiagramObjectCollection<UserHandle> handles = new DiagramObjectCollection<UserHandle>();
#pragma warning restore CS8618
public List<MindMapDetails> MindmapData = new List<MindMapDetails>()
{
new MindMapDetails(){Id="node1",Label="Business Planning",ParentId ="",Branch= BranchType.Root, Fill="#D0ECFF", Level = 0 },
new MindMapDetails(){Id="node2",Label= "Expectation",ParentId = "node1",Branch= BranchType.Left,Fill= "#C4F2E8", Level = 1 },
new MindMapDetails(){Id="node3",Label= "Requirements", ParentId="node1",Branch= BranchType.Right,Fill= "#F7E0B3", Level = 1 },
new MindMapDetails(){Id="node4",Label= "Marketing", ParentId="node1",Branch= BranchType.Left,Fill= "#E5FEE4", Level = 1 },
new MindMapDetails(){Id="node5",Label= "Budgets",ParentId= "node1",Branch= BranchType.Right,Fill= "#E9D4F1", Level = 1 },
new MindMapDetails(){ Id="node6", Label="Situation in Market", ParentId= "node1", Branch = BranchType.Left, Fill= "#D4EFED", Level = 1 },
new MindMapDetails(){ Id="node7", Label="Product Sales", ParentId= "node2", Branch = BranchType.SubLeft, Fill= "#C4F2E8", Level = 2 },
new MindMapDetails() { Id = "node8", Label= "Strategy", ParentId="node2", Branch = BranchType.SubLeft, Fill="#C4F2E8", Level = 2 },
new MindMapDetails() { Id = "node9", Label="Contacts", ParentId="node2", Branch = BranchType.SubLeft, Fill="#C4F2E8", Level = 2 },
new MindMapDetails() { Id = "node10", Label="Customer Groups", ParentId= "node4", Branch = BranchType.SubLeft,Fill= "#E5FEE4", Level = 2 },
new MindMapDetails() { Id = "node11", Label= "Branding", ParentId= "node4", Branch = BranchType.SubLeft, Fill= "#E5FEE4", Level = 2 },
new MindMapDetails() { Id = "node12", Label= "Advertising", ParentId= "node4", Branch = BranchType.SubLeft, Fill= "#E5FEE4", Level = 2 },
new MindMapDetails() { Id = "node13", Label= "Competitors", ParentId= "node6", Branch = BranchType.SubLeft, Fill="#D4EFED", Level = 2 },
new MindMapDetails() { Id = "node14", Label="Location", ParentId="node6", Branch = BranchType.SubLeft, Fill= "#D4EFED", Level = 2 },
new MindMapDetails() { Id = "node15", Label= "Director", ParentId= "node3", Branch = BranchType.SubRight, Fill="#F7E0B3", Level = 2 },
new MindMapDetails() { Id = "node16", Label="Accounts Department", ParentId= "node3", Branch = BranchType.SubRight, Fill= "#F7E0B3", Level = 2 },
new MindMapDetails() { Id = "node17", Label="Administration", ParentId= "node3", Branch = BranchType.SubRight, Fill="#F7E0B3", Level = 2 },
new MindMapDetails() { Id = "node18", Label= "Development", ParentId="node3", Branch = BranchType.SubRight, Fill= "#F7E0B3", Level = 2 },
new MindMapDetails() { Id = "node19", Label= "Estimation", ParentId= "node5", Branch = BranchType.SubRight, Fill="#E9D4F1", Level = 2 },
new MindMapDetails() { Id = "node20", Label= "Profit", ParentId= "node5", Branch = BranchType.SubRight, Fill= "#E9D4F1", Level = 2 },
new MindMapDetails(){ Id="node21", Label="Funds", ParentId= "node5", Branch = BranchType.SubRight, Fill= "#E9D4F1", Level = 2 }
};
public void StateChanged()
{
StateHasChanged();
}
private void CollectionChanging(CollectionChangingEventArgs args)
{
if (args.Action == CollectionChangedAction.Add && IsGeneratingFromAI)
{
Connector connector = args.Element as Connector;
if (connector != null)
{
UpdateMermaidNodeInfo(connector);
}
}
}
BranchType CurrentBranch = BranchType.Left;
private void UpdateMermaidNodeInfo(Connector connector)
{
Node sourceNode = Diagram.GetObject(connector.SourceID) as Node;
Node targetNode = Diagram.GetObject(connector.TargetID) as Node;
if (connector.ID == Diagram.Connectors[0].ID)
{
CurrentBranch = BranchType.Left;
sourceNode.AdditionalInfo["ParentId"] = "";
sourceNode.AdditionalInfo["Orientation"] = BranchType.Root;
sourceNode.AdditionalInfo["Level"] = 0;
sourceNode.Style.Fill = "#D0ECFF";
sourceNode.Style.StrokeColor = "#80BFEA";
}
if (sourceNode != null && (BranchType)sourceNode.AdditionalInfo["Orientation"] == BranchType.Root)
{
targetNode.AdditionalInfo["ParentId"] = sourceNode.ID;
targetNode.AdditionalInfo["Orientation"] = CurrentBranch;
targetNode.AdditionalInfo["Level"] = 1;
CurrentBranch = (CurrentBranch == BranchType.Left) ? BranchType.Right : BranchType.Left;
}
else
{
BranchType sourceNodeBranch = (BranchType)sourceNode.AdditionalInfo["Orientation"];
targetNode.AdditionalInfo["ParentId"] = sourceNode.ID;
targetNode.AdditionalInfo["Orientation"] = (sourceNodeBranch == BranchType.Left || sourceNodeBranch == BranchType.SubLeft) ? BranchType.SubLeft : BranchType.SubRight;
targetNode.AdditionalInfo["Level"] = Convert.ToDouble(sourceNode.AdditionalInfo["Level"]) + 1;
}
UpdateNodeStyles(targetNode, sourceNode);
BranchType targetNodeBranch = (BranchType)targetNode.AdditionalInfo["Orientation"];
if (targetNodeBranch == BranchType.Right || targetNodeBranch == BranchType.SubRight)
{
connector.SourcePortID = sourceNode.Ports[0].ID;
connector.TargetPortID = targetNode.Ports[1].ID;
}
else if (targetNodeBranch == BranchType.Left || targetNodeBranch == BranchType.SubLeft)
{
connector.SourcePortID = sourceNode.Ports[1].ID;
connector.TargetPortID = targetNode.Ports[0].ID;
}
}
/// <summary>
/// This Method to execute the custom command.
/// </summary>
public async Task ExecuteCommand(CommandKeyArgs obj)
{
if (obj.Name == "leftChild")
{
if (Diagram.SelectionSettings != null && Diagram.SelectionSettings.Nodes.Count > 0)
{
Diagram.StartGroupAction();
BranchType type = (BranchType)Diagram.SelectionSettings.Nodes[0].AdditionalInfo["Orientation"];
if (type == BranchType.SubRight || type == BranchType.Right)
{
await TextToMindMap.AddLeftChild(Diagram);
}
else if (type == BranchType.SubLeft || type == BranchType.Left || type == BranchType.Root)
{
await TextToMindMap.AddRightChild(Diagram);
}
Diagram.ClearSelection();
Diagram.Select(new ObservableCollection<IDiagramObject>() { Diagram.Nodes[Diagram.Nodes.Count - 1] });
Diagram.StartTextEdit(Diagram.Nodes[Diagram.Nodes.Count - 1]);
Diagram.EndGroupAction();
}
}
if (obj.Name == "rightChild")
{
if (Diagram.SelectionSettings != null && Diagram.SelectionSettings.Nodes.Count > 0)
{
Diagram.StartGroupAction();
BranchType type = (BranchType)Diagram.SelectionSettings.Nodes[0].AdditionalInfo["Orientation"];
if (type == BranchType.SubLeft || type == BranchType.Left)
{
await TextToMindMap.AddRightChild(Diagram);
}
else if (type == BranchType.SubRight || type == BranchType.Right || type == BranchType.Root)
{
await TextToMindMap.AddLeftChild(Diagram);
}
Diagram.ClearSelection();
Diagram.Select(new ObservableCollection<IDiagramObject>() { Diagram.Nodes[Diagram.Nodes.Count - 1] });
Diagram.StartTextEdit(Diagram.Nodes[Diagram.Nodes.Count - 1]);
Diagram.EndGroupAction();
}
}
if (obj.Name == "sibilingChildTop")
{
Node rootNode = Diagram.Nodes.Where(node => node.InEdges.Count == 0).ToList()[0];
if (rootNode.ID != Diagram.SelectionSettings.Nodes[0].ID)
{
Diagram.StartGroupAction();
string nodeParent = Convert.ToString(Diagram.SelectionSettings.Nodes[0].AdditionalInfo["ParentId"]);
string parentID = nodeParent;
Node parentNode = Diagram.GetObject(parentID) as Node;
BranchType branch = (BranchType)(parentNode.AdditionalInfo["Orientation"]);
BranchType nodeBranch = (BranchType)(Diagram.SelectionSettings.Nodes[0].AdditionalInfo["Orientation"]);
if (branch == BranchType.SubRight || branch == BranchType.Right || (branch == BranchType.Root && nodeBranch == BranchType.Right))
{
await TextToMindMap.AddLeftChild(Diagram, true);
}
else
{
await TextToMindMap.AddRightChild(Diagram, true);
}
Diagram.ClearSelection();
Diagram.Select(new ObservableCollection<IDiagramObject>() { Diagram.Nodes[Diagram.Nodes.Count - 1] });
Diagram.StartTextEdit(Diagram.Nodes[Diagram.Nodes.Count - 1]);
Diagram.EndGroupAction();
}
}
if (obj.Name == "navigationDown")
{
NavigateChild("Bottom");
}
if (obj.Name == "navigationUp")
{
NavigateChild("Top");
}
if (obj.Name == "navigationLeft")
{
NavigateChild("Right");
}
if (obj.Name == "navigationRight")
{
NavigateChild("Left");
}
if (obj.Name == "deleteChid" || obj.Name == "delete" || obj.Name == "backspace")
{
Diagram.BeginUpdate();
RemoveData(Diagram.SelectionSettings.Nodes[0], Diagram);
_ = Diagram.EndUpdateAsync();
await Diagram.DoLayoutAsync();
}
if (obj.Name == "fitPage")
{
FitOptions fitoption = new FitOptions()
{
Mode = FitMode.Both,
Region = DiagramRegion.PageSettings,
};
Diagram.FitToPage(fitoption);
}
if (obj.Name == "showShortCut")
{
ShowHideShortcutKey();
}
if (obj.Name == "duplicate")
{
MenubarRef.IsDuplicate = true;
Diagram.Copy();
Diagram.Paste(); MenubarRef.IsDuplicate = false;
}
if (obj.Name == "fileNew")
{
Diagram.Clear();
MenubarRef.enablePasteButten = false;
Diagram.BeginUpdate();
MenubarRef.ViewMenuItems[7].IconCss = "sf-icon-blank";
MenubarRef.WindowMenuItems[1].IconCss = "sf-icon-Selection";
DiagramShortCutKeyRef.ShowShortCutKey = "block";
Toolbar.PointerItemCssClass = "tb-item-middle tb-item-selected tb-item-pointer";
Toolbar.PanItemCssClass = "tb-item-start tb-item-pan";
await Toolbar.HideElements("hide-toolbar", true);
MenubarRef.WindowMenuItems[0].IconCss = "sf-icon-Selection";
Toolbar.StateChanged();
DiagramShortCutKeyRef.RefreshShortcutKeyPanel();
MenubarRef.ItemSelection();
StateHasChanged();
}
if (obj.Name == "fileOpen")
{
await MenubarRef.OpenUploadBox(true, ".json");
}
if (obj.Name == "fileSave")
{
string fileName = "diagram";
await MenubarRef.Download(fileName);
}
}
/// <summary>
/// This method is used to navigate between the nodes
/// </summary>
public void NavigateChild(string direction)
{
SfDiagramComponent diagram = Diagram;
Node? node = null;
List<Node> sameLevelNodes = new List<Node>();
if (direction == "Top" || direction == "Bottom")
{
sameLevelNodes = GetSameLevelNodes();
int index = sameLevelNodes.IndexOf(diagram.SelectionSettings.Nodes[0]);
node = direction == "Top" ? sameLevelNodes[index == 0 ? 0 : index - 1] : sameLevelNodes[index == (sameLevelNodes.Count - 1) ? index : index + 1];
}
else
node = GetMinDistanceNode(diagram, direction);
if (node != null)
{
diagram.Select(new ObservableCollection<IDiagramObject>() { node });
}
}
/// <summary>
/// This method is used to return a minimum distance node whie navigating between left and right
/// </summary>
private Node GetMinDistanceNode(SfDiagramComponent diagram, string direction)
{
Node node = diagram.SelectionSettings.Nodes[0];
double? nodeWidth = (node.Width == null) ? node.MinWidth : node.Width;
DiagramRect parentBounds = new DiagramRect((node.OffsetX - (nodeWidth / 2)), node.OffsetY - (node.Height / 2), nodeWidth, node.Height);
DiagramRect childBounds = new DiagramRect();
double oldChildBoundsTop = 0;
Node? childNode = null;
Node? lastChildNode = null;
Node? leftOrientationFirstChild = null;
Node? rightOrientationFirstChild = null;
Node rootNode = diagram.Nodes.Where(node => node.InEdges.Count == 0).ToList()[0];
if (node.ID == rootNode.ID)
{
List<string> edges = node.OutEdges;
for (int i = 0; i < edges.Count; i++)
{
Connector connector = GetConnector(diagram.Connectors, edges[i]);
childNode = GetNode(diagram.Nodes, connector.TargetID);
if (Convert.ToString((BranchType)childNode.AdditionalInfo["Orientation"]) == direction)
{
if (direction == "Left" && leftOrientationFirstChild == null)
leftOrientationFirstChild = childNode;
if (direction == "Right" && rightOrientationFirstChild == null)
rightOrientationFirstChild = childNode;
double? childNodeWidth = (childNode.Width == null) ? childNode.MinWidth : childNode.Width;
childBounds = new DiagramRect((childNode.OffsetX - (childNodeWidth / 2)), childNode.OffsetY - (childNode.Height / 2), childNodeWidth, childNode.Height);
if (parentBounds.Top >= childBounds.Top && (childBounds.Top >= oldChildBoundsTop || oldChildBoundsTop == 0))
{
oldChildBoundsTop = childBounds.Top;
lastChildNode = childNode;
}
}
}
if (lastChildNode != null)
lastChildNode = direction == "Left" ? leftOrientationFirstChild : rightOrientationFirstChild;
}
else
{
List<string> edges = new List<string>();
string selectType = string.Empty;
string orientation = ((BranchType)node.AdditionalInfo["Orientation"]).ToString();
if (orientation == "Left" || orientation == "SubLeft")
{
edges = direction == "Left" ? node.OutEdges : node.InEdges;
selectType = direction == "Left" ? "Target" : "Source";
}
else
{
edges = direction == "Right" ? node.OutEdges : node.InEdges;
selectType = direction == "Right" ? "Target" : "Source";
}
for (int i = 0; i < edges.Count; i++)
{
Connector connector = GetConnector(diagram.Connectors, edges[i]);
childNode = GetNode(diagram.Nodes, selectType == "Target" ? connector.TargetID : connector.SourceID);
if (childNode.ID == rootNode.ID)
lastChildNode = childNode;
else
{
double? childNodeWidth = (childNode.Width == null) ? childNode.MinWidth : childNode.Width;
childBounds = new DiagramRect((childNode.OffsetX - (childNodeWidth / 2)), childNode.OffsetY - (childNode.Height / 2), childNodeWidth, childNode.Height);
if (selectType == "Target")
{
if (parentBounds.Top >= childBounds.Top && (childBounds.Top >= oldChildBoundsTop || oldChildBoundsTop == 0))
{
oldChildBoundsTop = childBounds.Top;
lastChildNode = childNode;
}
}
else
lastChildNode = childNode;
}
}
}
return lastChildNode;
}
/// <summary>
/// This method is used to return a same level nodes
/// </summary>
private List<Node> GetSameLevelNodes()
{
List<Node> sameLevelNodes = new List<Node>();
SfDiagramComponent diagram = Diagram;
if (diagram.SelectionSettings.Nodes.Count > 0)
{
Node node = diagram.SelectionSettings.Nodes[0];
string orientation = ((BranchType)node.AdditionalInfo["Orientation"]).ToString();
Connector connector = GetConnector(diagram.Connectors, node.InEdges[0]);
Node parentNode = GetNode(diagram.Nodes, connector.SourceID);
for (int i = 0; i < parentNode.OutEdges.Count; i++)
{
connector = GetConnector(diagram.Connectors, parentNode.OutEdges[i]);
Node childNode = GetNode(diagram.Nodes, connector.TargetID);
if (childNode != null)
{
string childOrientation = Convert.ToString((BranchType)childNode.AdditionalInfo["Orientation"]);
if (orientation == childOrientation)
{
sameLevelNodes.Add(childNode);
}
}
}
}
return sameLevelNodes;
}
/// <summary>
/// This method is used to get the Nodes by connectors sourceID and targetID.
/// </summary>
public Node GetNode(DiagramObjectCollection<Node> diagramNodes, string name)
{
for (int i = 0; i < diagramNodes.Count; i++)
{
if (diagramNodes[i].ID == name)
{
return diagramNodes[i];
}
}
return null;
}
/// <summary>
/// This method is used to get the connectors by node's inedges and outedges
/// </summary>
public Connector GetConnector(DiagramObjectCollection<Connector> diagramConnectors, string name)
{
for (int i = 0; i < diagramConnectors.Count; i++)
{
if (diagramConnectors[i].ID == name)
{
return diagramConnectors[i];
}
}
return null;
}
/// <summary>
/// This method to determine whether this command can execute or not.
/// </summary>
public void CanExecute(CommandKeyArgs args)
{
args.CanExecute = true;
}
private BranchType getbranch(IDiagramObject obj)
{
Node node = obj as Node;
BranchType Branch = (BranchType)node.AdditionalInfo["Orientation"];
return Branch;
}
private void OnCreated()
{
Diagram.Select(new ObservableCollection<IDiagramObject>() { Diagram.Nodes[0] });
}
/// <summary>
/// This method is triggered when select or deselect any objects from the diagram. .
/// </summary>
private void SelectionChanged(Syncfusion.Blazor.Diagram.SelectionChangedEventArgs args)
{
Toolbar.EnableToolbarItems(args.NewValue, "selectionchange");
int ObjectsLength = Diagram.SelectionSettings.Nodes.Count + Diagram.SelectionSettings.Connectors.Count;
if (ObjectsLength > 1 && (Diagram.SelectionSettings.Nodes.Count > 0 || (Diagram.SelectionSettings.Connectors.Count > 0)))
{
diagramSelected = false;
this.MultipleSelectionSettings(args.NewValue);
}
else if (ObjectsLength == 1 && (Diagram.SelectionSettings.Nodes.Count == 1 || Diagram.SelectionSettings.Connectors.Count == 1))
{
Toolbar.SingleSelectionToolbarItems();
}
else
{
diagramSelected = true;
Toolbar.DiagramSelectionToolbarItems();
}
}
/// <summary>
/// This method is used to enable the toolbar items in diagram interaction.
/// </summary>
private void HistoryChange(HistoryChangedEventArgs args)
{
Toolbar.EnableToolbarItems(new object() { }, "historychange");
}
/// <summary>
/// This method is used to enable the tool bar items in multiple selection.
/// </summary>
private void MultipleSelectionSettings(ObservableCollection<IDiagramObject> SelectedItems)
{
Toolbar.MutipleSelectionToolbarItems();
}
/// <summary>
/// This method is used show or hide the shortcut key.
/// </summary>
public void ShowHideShortcutKey()
{
DiagramShortCutKeyRef.ShowShortCutKey = DiagramShortCutKeyRef.ShowShortCutKey == "none" ? "block" : "none";
int shortcutIndex = MenubarRef.WindowMenuItems.FindIndex(item => item.Text == "Show Shortcuts");
MenubarRef.WindowMenuItems[shortcutIndex].IconCss = MenubarRef.WindowMenuItems[shortcutIndex].IconCss == "sf-icon-blank" ? "sf-icon-Selection" : "sf-icon-blank";
MenubarRef.StateChanged();
DiagramShortCutKeyRef.RefreshShortcutKeyPanel();
}
private void ScrollChanged()
{
if (CurrentZoom >= 0.25 && CurrentZoom <= 30)
{
Toolbar.ZoomItemDropdownContent = FormattableString.Invariant($"{Math.Round(CurrentZoom * 100)}") + "%";
Toolbar.StateChanged();
}
}
// Method to customize the tool
public InteractionControllerBase GetCustomTool(DiagramElementAction action, string id)
{
InteractionControllerBase tool = null;
if (id == "AddLeft")
{
tool = new AddRightTool(Diagram);
}
else if (id == "AddRight")
{
tool = new AddLeftTool(Diagram);
}
else
{
tool = new DeleteTool(Diagram);
}
return tool;
}
public static async Task AddRightChild(SfDiagramComponent diagram, bool isSibling = false)
{
string newChildID = RandomId();
string newchildColor = ""; BranchType type = BranchType.Left; Node parentNode = null;
string parentId = Convert.ToString(diagram.SelectionSettings.Nodes[0].AdditionalInfo["ParentId"]);
BranchType nodeBranch = (BranchType)diagram.SelectionSettings.Nodes[0].AdditionalInfo["Orientation"];
double currentLevel = Convert.ToDouble(diagram.SelectionSettings.Nodes[0].AdditionalInfo["Level"]);
double parentLevel = 0;
if (!string.IsNullOrEmpty(parentId))
{
parentNode = diagram.GetObject(parentId) as Node;
BranchType parentNodeBranch = (BranchType)parentNode.AdditionalInfo["Orientation"];
type = isSibling ? parentNodeBranch : nodeBranch;
}
else
{
type = nodeBranch;
}
BranchType childType = BranchType.Left;
if (parentNode != null) parentLevel = Convert.ToDouble(parentNode.AdditionalInfo["Level"]);
switch (type.ToString())
{
case "Root":
childType = BranchType.Left;
break;
case "Left":
childType = BranchType.SubLeft;
break;
case "SubLeft":
childType = BranchType.SubLeft;
break;
}
double level = isSibling ? parentLevel : currentLevel;
if (level == 0)
{
int index = Convert.ToInt32(GetFillColorIndex(level));
newchildColor = fillColorCode[index];
}
else
{
newchildColor = diagram.SelectionSettings.Nodes[0].Style.Fill;
}
MindMapDetails childNode = new MindMapDetails()
{
Id = newChildID.ToString(),
ParentId = isSibling ? parentId : diagram.SelectionSettings.Nodes[0].ID,
Fill = newchildColor,
Branch = childType,
Label = "New Child",
Level = isSibling ? parentLevel + 1 : currentLevel + 1
};
diagram.BeginUpdate();
await UpdatePortConnection(childNode, diagram, isSibling);
await diagram.EndUpdateAsync();
}
// Custom tool to add the node.
public class AddLeftTool : InteractionControllerBase
{
SfDiagramComponent diagram;
public AddLeftTool(SfDiagramComponent Diagram) : base(Diagram)
{
diagram = Diagram;
}
public override async void OnMouseDown(DiagramMouseEventArgs args)
{
await AddRightChild(diagram);
diagram.ClearSelection();
base.OnMouseDown(args);
diagram.Select(new ObservableCollection<IDiagramObject>() { diagram.Nodes[diagram.Nodes.Count - 1] });
diagram.StartTextEdit(diagram.Nodes[diagram.Nodes.Count - 1]);
this.InAction = true;
}
}
private static async Task UpdatePortConnection(MindMapDetails childNode, SfDiagramComponent diagram, bool isSibling)
{
Node node = new Node()
{
ID = "node" + childNode.Id,
Height = 50,
Width = 100,
Annotations = new DiagramObjectCollection<ShapeAnnotation>()
{
new ShapeAnnotation()
{
Content = childNode.Label,
Style=new TextStyle(){FontSize = 12,FontFamily="Segoe UI"},
Offset=new DiagramPoint(){X=0.5,Y=0.5}
}
},
Style = new ShapeStyle() { Fill = childNode.Fill, StrokeColor = childNode.Fill },
AdditionalInfo = new Dictionary<string, object>()
{
{"Orientation", childNode.Branch},
{"ParentId", childNode.ParentId},
{"Level", childNode.Level},
}
};
Connector connector = new Connector()
{
TargetID = node.ID,
SourceID = isSibling ? childNode.ParentId : diagram.SelectionSettings.Nodes[0].ID
};
await diagram.AddDiagramElementsAsync(new DiagramObjectCollection<NodeBase>() { node, connector });
Node sourceNode = diagram.GetObject((connector as Connector).SourceID) as Node;
Node targetNode = diagram.GetObject((connector as Connector).TargetID) as Node;
if (targetNode != null && targetNode.AdditionalInfo.Count > 0)
{
BranchType nodeBranch = (BranchType)targetNode.AdditionalInfo["Orientation"];
if (nodeBranch == BranchType.Right || nodeBranch == BranchType.SubRight)
{
(connector as Connector).SourcePortID = sourceNode.Ports[0].ID;
(connector as Connector).TargetPortID = targetNode.Ports[1].ID;
}
else if (nodeBranch == BranchType.Left || nodeBranch == BranchType.SubLeft)
{
(connector as Connector).SourcePortID = sourceNode.Ports[1].ID;
(connector as Connector).TargetPortID = targetNode.Ports[0].ID;
}
}
await diagram.DoLayoutAsync();
}
public void ZoomTo(ZoomOptions options)
{
double factor = options.ZoomFactor != 0 ? options.ZoomFactor : 0.2;
factor = options.Type == "ZoomOut" ? 1 / (1 + factor) : (1 + factor);
Diagram.Zoom(factor, null);
}
/// <summary>
/// This method is used to allows users to pan the diagram.
/// </summary>
public void UpdateTool()
{
interactionController = DiagramInteractions.ZoomPan;
StateHasChanged();
}
/// <summary>
/// This method is used to allows users to perform selection in the diagram.
/// </summary>
public void UpdatePointerTool()
{
interactionController = DiagramInteractions.SingleSelect;
StateHasChanged();
}
/// <summary>
/// Represents the zoom option in a diagram.
/// </summary>
public class ZoomOptions
{
public double ZoomFactor { get; set; }
public string Type { get; set; }
}
public static async Task AddLeftChild(SfDiagramComponent diagram, bool isSibling = false)
{
string newChildID = RandomId();
string newchildColor = ""; BranchType type = BranchType.Left; Node parentNode = null;
string parentId = Convert.ToString(diagram.SelectionSettings.Nodes[0].AdditionalInfo["ParentId"]);
BranchType nodeBranch = (BranchType)diagram.SelectionSettings.Nodes[0].AdditionalInfo["Orientation"];
double currentLevel = Convert.ToDouble(diagram.SelectionSettings.Nodes[0].AdditionalInfo["Level"]);
double parentLevel = 0;
if (!string.IsNullOrEmpty(parentId))
{
parentNode = diagram.GetObject(parentId) as Node;
BranchType parentNodeBranch = (BranchType)parentNode.AdditionalInfo["Orientation"];
type = isSibling ? parentNodeBranch : nodeBranch;
}
else
{
type = nodeBranch;
}
BranchType childType = BranchType.Left;
if (parentNode != null) parentLevel = Convert.ToDouble(parentNode.AdditionalInfo["Level"]);
switch (type.ToString())
{
case "Root":
childType = BranchType.Right;
break;
case "Right":
childType = BranchType.SubRight;
break;
case "SubRight":
childType = BranchType.SubRight;
break;
}
double level = isSibling ? parentLevel : currentLevel;
if (level == 0)
{
int index = Convert.ToInt32(GetFillColorIndex(level));
newchildColor = fillColorCode[index];
}
else
{
newchildColor = diagram.SelectionSettings.Nodes[0].Style.Fill;
}
MindMapDetails childNode = new MindMapDetails()
{
Id = newChildID.ToString(),
ParentId = isSibling ? parentId : diagram.SelectionSettings.Nodes[0].ID,
Fill = newchildColor,
Branch = childType,
Label = "New Child",
Level = isSibling ? parentLevel + 1 : currentLevel + 1
};
diagram.BeginUpdate();
await UpdatePortConnection(childNode, diagram, isSibling);
await diagram.EndUpdateAsync();
}
// Custom tool to add the node.
public class AddRightTool : InteractionControllerBase
{
SfDiagramComponent diagram;
public AddRightTool(SfDiagramComponent Diagram) : base(Diagram)
{
diagram = Diagram;
}
public override async void OnMouseDown(DiagramMouseEventArgs args)
{
await AddLeftChild(diagram);
diagram.ClearSelection();
base.OnMouseDown(args);
diagram.Select(new ObservableCollection<IDiagramObject>() { diagram.Nodes[diagram.Nodes.Count - 1] });
diagram.StartTextEdit(diagram.Nodes[diagram.Nodes.Count - 1]);
this.InAction = true;
}
}
public class DeleteTool : InteractionControllerBase
{
SfDiagramComponent sfDiagram;
Node deleteObject = null;
public DeleteTool(SfDiagramComponent Diagram) : base(Diagram)
{
sfDiagram = Diagram;
}
public override void OnMouseDown(DiagramMouseEventArgs args)
{
deleteObject = (sfDiagram.SelectionSettings.Nodes[0]) as Node;
}
public override async void OnMouseUp(DiagramMouseEventArgs args)
{
if (deleteObject != null)
{
sfDiagram.BeginUpdate();
RemoveData(deleteObject, sfDiagram);
_ = sfDiagram.EndUpdateAsync();
await sfDiagram.DoLayoutAsync();
}
base.OnMouseUp(args);
this.InAction = true;
}
}
private static void RemoveData(Node node, SfDiagramComponent diagram)
{
if (node.OutEdges.Count > 0)
{
List<string> outEdges = new List<string>();
node.OutEdges.ForEach(edges => outEdges.Add(edges));
for (int i = 0; i < outEdges.Count; i++)
{
Connector connector = diagram.GetObject(outEdges[i]) as Connector;
Node targetnode = diagram.GetObject(connector.TargetID) as Node;
if (targetnode.OutEdges.Count > 0)
{
RemoveData(targetnode, diagram);
}
else
{
diagram.Delete(new DiagramObjectCollection<NodeBase>() { targetnode });
}
}
diagram.Delete(new DiagramObjectCollection<NodeBase>() { node });
}
else
{
diagram.Delete(new DiagramObjectCollection<NodeBase>() { node });
}
}
private void OnSelectionChanging(SelectionChangingEventArgs args)
{
if (args.NewValue.Count > 0)
{
if (args.NewValue[0] is Node && (args.NewValue[0] as Node).AdditionalInfo.Count > 0)
{
BranchType type = (BranchType)((args.NewValue[0] as Node).AdditionalInfo["Orientation"]);
if (type == BranchType.Root)
{
selectionSettings.UserHandles[0].Visible = false;
selectionSettings.UserHandles[1].Visible = false;
selectionSettings.UserHandles[2].Visible = true;
selectionSettings.UserHandles[3].Visible = true;
}
else if (type == BranchType.Left || type == BranchType.SubLeft)
{
selectionSettings.UserHandles[0].Visible = false;
selectionSettings.UserHandles[1].Visible = true;
selectionSettings.UserHandles[2].Visible = true;
selectionSettings.UserHandles[3].Visible = false;
}
else if (type == BranchType.Right || type == BranchType.SubRight)
{
selectionSettings.UserHandles[0].Visible = true;
selectionSettings.UserHandles[1].Visible = false;
selectionSettings.UserHandles[2].Visible = false;
selectionSettings.UserHandles[3].Visible = true;
}
}
}
}
private void NodeCreating(IDiagramObject obj)
{
Node node = obj as Node;
node.Height = 50;
node.Width = 100;
node.Shape = new BasicShape() { Type = Shapes.Basic, Shape = NodeBasicShapes.Ellipse };
PointPort port21 = new PointPort()
{
ID = "left",
Offset = new DiagramPoint() { X = 0, Y = 0.5 },
Height = 10,
Width = 10,
};
PointPort port22 = new PointPort()
{
ID = "right",
Offset = new DiagramPoint() { X = 1, Y = 0.5 },
Height = 10,
Width = 10,
};
node.Ports = new DiagramObjectCollection<PointPort>()
{
port21,port22
};
if (MenubarRef.IsJsonLoading)
{
if (node.AdditionalInfo["Level"] is JsonElement level)
{
double levelString = level.GetDouble();
node.AdditionalInfo["Level"] = levelString;
}
if (node.AdditionalInfo["Orientation"] is JsonElement orientation)
{
int orientationValue = orientation.GetInt32();
BranchType branch = (BranchType)orientationValue;
node.AdditionalInfo["Orientation"] = branch;
}
if (node.AdditionalInfo["ParentId"] is JsonElement parentId)
{
string parent = parentId.GetString();
node.AdditionalInfo["ParentId"] = parent;
}
}
node.Constraints &= ~NodeConstraints.Rotate;
}
private void ConnectorCreating(IDiagramObject obj)
{
Connector connector = obj as Connector;
connector.Type = ConnectorSegmentType.Bezier;
connector.BezierConnectorSettings = new BezierConnectorSettings() { AllowSegmentsReset = false };
connector.Constraints = ConnectorConstraints.Default & ~ConnectorConstraints.Select;
connector.Style = new ShapeStyle() { StrokeColor = "#4f4f4f", StrokeWidth = 1 };
connector.TargetDecorator = new DecoratorSettings() { Shape = DecoratorShape.None };
connector.SourceDecorator.Shape = DecoratorShape.None;
Node sourceNode = Diagram.GetObject((connector as Connector).SourceID) as Node;
Node targetNode = Diagram.GetObject((connector as Connector).TargetID) as Node;
if (targetNode != null && targetNode.AdditionalInfo.Count > 0)
{
BranchType nodeBranch = (BranchType)targetNode.AdditionalInfo["Orientation"];
if (nodeBranch == BranchType.Right || nodeBranch == BranchType.SubRight)
{
(connector as Connector).SourcePortID = sourceNode.Ports[0].ID;
(connector as Connector).TargetPortID = targetNode.Ports[1].ID;
}
else if (nodeBranch == BranchType.Left || nodeBranch == BranchType.SubLeft)
{