Skip to content

Commit 6f01668

Browse files
committed
Fixed Subgraph logic.
1 parent b1ee440 commit 6f01668

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/Mermaid.Flowcharts/Subgraphs/Subgraph.cs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public record Subgraph : INode<Subgraph>
1616
public IEnumerable<Node> Nodes => _nodes.OfType<Node>();
1717
public IEnumerable<Subgraph> Subgraphs => _nodes.OfType<Subgraph>();
1818
public IEnumerable<Link> Links => _links.AsReadOnly();
19+
public IEnumerable<INode> AllNodeChildren => _nodes.Concat(Subgraphs.SelectMany(subgraph => subgraph._nodes));
1920
public IEnumerable<Node> AllNodes => Nodes.Concat(Subgraphs.SelectMany(subgraph => subgraph.AllNodes));
2021
public IEnumerable<Link> AllLinks => Links.Concat(Subgraphs.SelectMany(subgraph => subgraph.AllLinks));
2122

@@ -50,6 +51,11 @@ public static Subgraph Create(string identifier, string title, SubgraphDirection
5051

5152
public Subgraph AddNode(INode node)
5253
{
54+
if (Equals(node))
55+
{
56+
throw new ArgumentException("Cannot add subgraph as a node to itself.", nameof(node));
57+
}
58+
5359
if (node is Node nd && Nodes.Any(nd.Equals))
5460
{
5561
return this;
@@ -61,10 +67,12 @@ public Subgraph AddNode(INode node)
6167

6268
public Subgraph AddLink(Link link)
6369
{
64-
_links.Add(link);
65-
AddNode(link.Source);
66-
AddNode(link.Destination);
67-
return this;
70+
if (AllNodeChildren.Any(link.Source.Equals) && AllNodeChildren.Any(link.Destination.Equals))
71+
{
72+
_links.Add(link);
73+
return this;
74+
}
75+
throw new InvalidOperationException("Cannot add link to subgraph: the source and the destination nodes should both be present within the subgraph.");
6876
}
6977

7078
public override string ToString()

0 commit comments

Comments
 (0)