@@ -21,7 +21,7 @@ let startY = 0;
2121 * @param sm
2222 * @returns Mermaid diagram string
2323 */
24- export function createMermaidDiagram ( sm : LJStateMachine | undefined , orientation : "LR" | "TB" ) : string {
24+ export function createMermaidDiagram ( sm : LJStateMachine | undefined , orientation : "LR" | "TB" , showConditions = false ) : string {
2525 if ( ! sm ) return '' ;
2626
2727 const lines : string [ ] = [ ] ;
@@ -33,17 +33,19 @@ export function createMermaidDiagram(sm: LJStateMachine | undefined, orientation
3333 lines . push ( 'stateDiagram-v2' ) ;
3434 lines . push ( ` direction ${ orientation } ` ) ;
3535
36- // initial states
37- sm . initialStates . forEach ( state => {
38- lines . push ( ` [*] --> ${ state } ` ) ;
36+ // initial transitions
37+ sm . initialTransitions . forEach ( transition => {
38+ const label = getInitialTransitionLabel ( transition . postCond , showConditions ) ;
39+ lines . push ( ` [*] --> ${ transition . to } ${ label ? ` : ${ label } ` : '' } ` ) ;
3940 } ) ;
4041
4142 // group transitions by from/to states and merge labels
4243 const transitionMap = new Map < string , string [ ] > ( ) ;
4344 sm . transitions . forEach ( transition => {
45+ const label = getTransitionLabel ( transition . label , transition . preCond , transition . postCond , showConditions ) ;
4446 const key = `${ transition . from } |${ transition . to } ` ;
4547 if ( ! transitionMap . has ( key ) ) transitionMap . set ( key , [ ] ) ;
46- transitionMap . get ( key ) ?. push ( transition . label ) ;
48+ transitionMap . get ( key ) ?. push ( label ) ;
4749 } ) ;
4850
4951 // add transitions
@@ -56,6 +58,33 @@ export function createMermaidDiagram(sm: LJStateMachine | undefined, orientation
5658 return lines . join ( '\n' ) ;
5759}
5860
61+ function getTransitionLabel ( label : string , preCond ?: string | null , postCond ?: string | null , showConditions = false ) : string {
62+ if ( ! showConditions ) {
63+ return escapeMermaidLabel ( label ) ;
64+ }
65+
66+ return [
67+ getConditionLabel ( 'pre' , preCond ) ,
68+ escapeMermaidLabel ( label ) ,
69+ getConditionLabel ( 'post' , postCond )
70+ ] . filter ( Boolean ) . join ( '<br/>' ) ;
71+ }
72+
73+ function getInitialTransitionLabel ( postCond ?: string | null , showConditions = false ) : string {
74+ return showConditions ? getConditionLabel ( 'post' , postCond ) : '' ;
75+ }
76+
77+ function getConditionLabel ( kind : 'pre' | 'post' , cond ?: string | null ) : string {
78+ if ( ! cond ) {
79+ return '' ;
80+ }
81+ return `<span class="state-cond state-cond-${ kind } ">${ escapeMermaidLabel ( cond ) } </span>` ;
82+ }
83+
84+ function escapeMermaidLabel ( label : string ) : string {
85+ return label . replace ( / & / g, '&' ) . replace ( / " / g, '\\"' ) . replace ( / < / g, '<' ) . replace ( / > / g, '>' ) ;
86+ }
87+
5988/**
6089 * Renders Mermaid diagrams in the document
6190 * @param document The document object
0 commit comments