Skip to content

Commit

Permalink
graphviz: Highlight current state instead of drawing it first (#84)
Browse files Browse the repository at this point in the history
We want to have a stable graph output.

Signed-off-by: Benjamin Imhof <[email protected]>
  • Loading branch information
baw-benji authored Jul 15, 2022
1 parent 0b86adf commit 13de56e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
30 changes: 12 additions & 18 deletions graphviz_visualizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ func Visualize(fsm *FSM) string {
sortedStateKeys, _ := getSortedStates(fsm.transitions)

writeHeaderLine(&buf)
writeTransitions(&buf, fsm.current, sortedEKeys, fsm.transitions)
writeStates(&buf, sortedStateKeys)
writeTransitions(&buf, sortedEKeys, fsm.transitions)
writeStates(&buf, fsm.current, sortedStateKeys)
writeFooter(&buf)

return buf.String()
Expand All @@ -26,29 +26,23 @@ func writeHeaderLine(buf *bytes.Buffer) {
buf.WriteString("\n")
}

func writeTransitions(buf *bytes.Buffer, current string, sortedEKeys []eKey, transitions map[eKey]string) {
// make sure the current state is at top
func writeTransitions(buf *bytes.Buffer, sortedEKeys []eKey, transitions map[eKey]string) {
for _, k := range sortedEKeys {
if k.src == current {
v := transitions[k]
buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
buf.WriteString("\n")
}
}
for _, k := range sortedEKeys {
if k.src != current {
v := transitions[k]
buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
buf.WriteString("\n")
}
v := transitions[k]
buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
buf.WriteString("\n")
}

buf.WriteString("\n")
}

func writeStates(buf *bytes.Buffer, sortedStateKeys []string) {
func writeStates(buf *bytes.Buffer, current string, sortedStateKeys []string) {
for _, k := range sortedStateKeys {
buf.WriteString(fmt.Sprintf(` "%s";`, k))
if k == current {
buf.WriteString(fmt.Sprintf(` "%s" [color = "red"];`, k))
} else {
buf.WriteString(fmt.Sprintf(` "%s";`, k))
}
buf.WriteString("\n")
}
}
Expand Down
2 changes: 1 addition & 1 deletion graphviz_visualizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ digraph fsm {
"intermediate" -> "closed" [ label = "part-close" ];
"open" -> "closed" [ label = "close" ];
"closed";
"closed" [color = "red"];
"intermediate";
"open";
}`
Expand Down

0 comments on commit 13de56e

Please sign in to comment.