Skip to content

Commit

Permalink
Merge pull request #75 from jmichaud/jmichaud/add_event_labels_to_export
Browse files Browse the repository at this point in the history
Proposal to add the option to use event class names as transition labels in PlantUML export
  • Loading branch information
nsk90 authored Dec 5, 2023
2 parents e5311b3 + bd423fe commit 84446a6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,7 @@ to [PlantUML state diagram](https://plantuml.com/en/state-diagram).
```kotlin
val machine = createStateMachine(scope) { /* ... */ }
println(machine.exportToPlantUml())
println(machine.exportToPlantUml(showEventLabels = false))
```
Copy/paste resulting output to [Plant UML online editor](http://www.plantuml.com/plantuml/)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import ru.nsk.kstatemachine.TransitionDirectionProducerPolicy.CollectTargetState
*
* Conditional transitions currently are not supported.
*/
internal class ExportPlantUmlVisitor : CoVisitor {
internal class ExportPlantUmlVisitor(val showEventLabels: Boolean = false) : CoVisitor {
private val builder = StringBuilder()
private var indent = 0
private val crossLevelTransitions = mutableListOf<String>()
Expand Down Expand Up @@ -69,7 +69,8 @@ internal class ExportPlantUmlVisitor : CoVisitor {
targetState.graphName()
}

val transitionString = "$sourceState --> $graphName${label(transition.name)}"
val eventLabel = if(showEventLabels) transition.eventMatcher.eventClass.simpleName else null
val transitionString = "$sourceState --> $graphName${label(transition.name, eventLabel)}"

if (transition.sourceState.isNeighbor(targetState))
line(transitionString)
Expand Down Expand Up @@ -114,17 +115,19 @@ internal class ExportPlantUmlVisitor : CoVisitor {
return if (this !is StateMachine) name else "${name}_StateMachine"
}

fun label(name: String?) = if (name != null) " : $name" else ""
fun label(name: String?, eventName: String? = null) =
if (name == null && eventName == null) "" else
" :${name?.let { " $it" } ?: ""}${eventName?.let { " $it" } ?: ""}"
}
}

suspend fun StateMachine.exportToPlantUml() = with(ExportPlantUmlVisitor()) {
suspend fun StateMachine.exportToPlantUml(showEventLabels: Boolean = false) = with(ExportPlantUmlVisitor(showEventLabels)) {
accept(this)
export()
}

fun StateMachine.exportToPlantUmlBlocking() = coroutineAbstraction.runBlocking {
with(ExportPlantUmlVisitor()) {
fun StateMachine.exportToPlantUmlBlocking(showEventLabels: Boolean = false) = coroutineAbstraction.runBlocking {
with(ExportPlantUmlVisitor(showEventLabels)) {
accept(this)
export()
}
Expand Down

0 comments on commit 84446a6

Please sign in to comment.