I have a complex Mermaid diagram with many different subgraphs. It is large enough that it is hard to keep track of the order of different subgraphs. Sometimes I reorder them for clarity or positioning.
Unfortunately, the order of the subgraphs is important because the first time a node appears in the Markdown determines the subgraph that the Node will be a part of.
For instance, the following code:
flowchart LR
subgraph Subgraph 1
A
end
subgraph Subgraph 2
A --> B
end
Renders as:
Whereas the same code with the subgraphs reordered:
flowchart LR
subgraph Subgraph 2
A --> B
end
subgraph Subgraph 1
A
end
Renders differently:
Is there a way to mark a node as permanently anchored to a certain subgraph, in a way that is persistent across re-ordering the subgraphs?
For instance, it would be great if there was something like A$
in which the $
indicates that Node A should always be part of that subgraph.
Hello @canary_in_the_data_mine, thank you for your interesting question!
I initially found setting up subgraphs to be somewhat challenging due to the syntax being unclear at first glance. However, I developed a general principle that a node belongs to the first subgraph in which it appears. In your second example, this means that A and B are placed in Subgraph2 while Subgraph1 is empty and treated as a regular node.
By following this guideline, you can easily lock nodes to their respective subgraphs and even add links outside of the subgraphs. Here is an example of how to do this:
flowchart LR
subgraph Subgraph 2
B
end
subgraph Subgraph 1
A
end
A-->B
Your question is great because it highlights a potential area of confusion. With the rule for placing nodes in subgraphs in mind, the syntax becomes much clearer.