forked from looplab/fsm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualizer.go
77 lines (67 loc) · 2.54 KB
/
visualizer.go
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
package fsm
import (
"fmt"
"sort"
)
// VisualizeType the type of the visualization
type VisualizeType string
const (
// GRAPHVIZ the type for graphviz output (http://www.webgraphviz.com/)
GRAPHVIZ VisualizeType = "graphviz"
// MERMAID the type for mermaid output (https://mermaid-js.github.io/mermaid/#/stateDiagram) in the stateDiagram form
MERMAID VisualizeType = "mermaid"
// MermaidStateDiagram the type for mermaid output (https://mermaid-js.github.io/mermaid/#/stateDiagram) in the stateDiagram form
MermaidStateDiagram VisualizeType = "mermaid-state-diagram"
// MermaidFlowChart the type for mermaid output (https://mermaid-js.github.io/mermaid/#/flowchart) in the flow chart form
MermaidFlowChart VisualizeType = "mermaid-flow-chart"
)
// VisualizeWithType outputs a visualization of a FSM in the desired format.
// If the type is not given it defaults to GRAPHVIZ
func VisualizeWithType(fsm *FSM, visualizeType VisualizeType) (string, error) {
switch visualizeType {
case GRAPHVIZ:
return Visualize(fsm), nil
case MERMAID:
return VisualizeForMermaidWithGraphType(fsm, StateDiagram)
case MermaidStateDiagram:
return VisualizeForMermaidWithGraphType(fsm, StateDiagram)
case MermaidFlowChart:
return VisualizeForMermaidWithGraphType(fsm, FlowChart)
default:
return "", fmt.Errorf("unknown VisualizeType: %s", visualizeType)
}
}
func getSortedTransitionKeys(transitions map[eKey]string) []eKey {
// we sort the key alphabetically to have a reproducible graph output
sortedTransitionKeys := make([]eKey, 0)
for transition := range transitions {
sortedTransitionKeys = append(sortedTransitionKeys, transition)
}
sort.Slice(sortedTransitionKeys, func(i, j int) bool {
if sortedTransitionKeys[i].src == sortedTransitionKeys[j].src {
return sortedTransitionKeys[i].event < sortedTransitionKeys[j].event
}
return sortedTransitionKeys[i].src < sortedTransitionKeys[j].src
})
return sortedTransitionKeys
}
func getSortedStates(transitions map[eKey]string) ([]string, map[string]string) {
statesToIDMap := make(map[string]string)
for transition, target := range transitions {
if _, ok := statesToIDMap[transition.src]; !ok {
statesToIDMap[transition.src] = ""
}
if _, ok := statesToIDMap[target]; !ok {
statesToIDMap[target] = ""
}
}
sortedStates := make([]string, 0, len(statesToIDMap))
for state := range statesToIDMap {
sortedStates = append(sortedStates, state)
}
sort.Strings(sortedStates)
for i, state := range sortedStates {
statesToIDMap[state] = fmt.Sprintf("id%d", i)
}
return sortedStates, statesToIDMap
}