state.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. // Package renderer provides rendering functionality for state diagrams
  2. package renderer
  3. import (
  4. "fmt"
  5. "strings"
  6. "mermaid-go/pkg/ast"
  7. )
  8. // StateRenderer renders state diagrams back to mermaid syntax
  9. type StateRenderer struct{}
  10. // NewStateRenderer creates a new state renderer
  11. func NewStateRenderer() *StateRenderer {
  12. return &StateRenderer{}
  13. }
  14. // Render renders a state diagram to mermaid syntax
  15. func (r *StateRenderer) Render(diagram *ast.StateDiagram) (string, error) {
  16. var builder strings.Builder
  17. // Start with diagram declaration
  18. builder.WriteString("stateDiagram-v2\n")
  19. // Add title if present
  20. if diagram.Title != nil {
  21. builder.WriteString(fmt.Sprintf(" title %s\n", *diagram.Title))
  22. }
  23. // Add direction if present
  24. if diagram.Direction != "" {
  25. builder.WriteString(fmt.Sprintf(" direction %s\n", diagram.Direction))
  26. }
  27. // Create a map to track which states need explicit declaration
  28. stateNeedsDeclaration := make(map[string]bool)
  29. // Check which states need explicit declaration
  30. for _, state := range diagram.States {
  31. needsDeclaration := false
  32. // State needs declaration if it has special type, alias, or description
  33. if state.Type != ast.StateTypeDefault || state.Label != state.ID || state.Description != nil {
  34. needsDeclaration = true
  35. }
  36. // State needs declaration if it has composite structure
  37. if len(state.SubStates) > 0 {
  38. needsDeclaration = true
  39. }
  40. stateNeedsDeclaration[state.ID] = needsDeclaration
  41. }
  42. // Separate transitions into external and internal
  43. var externalTransitions []*ast.StateTransition
  44. var internalTransitions = make(map[string][]*ast.StateTransition) // stateID -> transitions
  45. for _, transition := range diagram.Transitions {
  46. // Check if this is an internal transition (both states are within the same composite state)
  47. isInternal := false
  48. for _, state := range diagram.States {
  49. if len(state.SubStates) > 0 {
  50. fromInState := r.isStateInComposite(state, transition.From)
  51. toInState := r.isStateInComposite(state, transition.To)
  52. if fromInState && toInState {
  53. internalTransitions[state.ID] = append(internalTransitions[state.ID], transition)
  54. isInternal = true
  55. break
  56. }
  57. }
  58. }
  59. if !isInternal {
  60. externalTransitions = append(externalTransitions, transition)
  61. }
  62. }
  63. // Separate states into special states and others
  64. var specialStates []*ast.StateNode
  65. var otherStates []*ast.StateNode
  66. for _, state := range diagram.States {
  67. if stateNeedsDeclaration[state.ID] {
  68. // Check if this is a special state
  69. if state.Type == ast.StateTypeFork || state.Type == ast.StateTypeJoin ||
  70. state.Type == ast.StateTypeChoice || state.Type == ast.StateTypeHistory ||
  71. state.Type == ast.StateTypeDeepHistory {
  72. specialStates = append(specialStates, state)
  73. } else {
  74. otherStates = append(otherStates, state)
  75. }
  76. }
  77. }
  78. // Render special states first (sorted by type priority)
  79. r.sortStatesByTransitionOrder(specialStates, diagram.Transitions)
  80. for _, state := range specialStates {
  81. r.renderStateWithInternalTransitions(&builder, state, internalTransitions[state.ID])
  82. }
  83. // Render [*] --> state transitions
  84. for _, transition := range externalTransitions {
  85. if transition.From == "[*]" {
  86. r.renderTransition(&builder, transition)
  87. }
  88. }
  89. // Render other states that need explicit declaration (composite states, etc.)
  90. for _, state := range otherStates {
  91. r.renderStateWithInternalTransitions(&builder, state, internalTransitions[state.ID])
  92. }
  93. // Render state actions for states that don't need explicit declaration
  94. for _, state := range diagram.States {
  95. if !stateNeedsDeclaration[state.ID] {
  96. r.renderStateActions(&builder, state)
  97. }
  98. }
  99. // Render other external transitions (state --> [*] and state --> state)
  100. for _, transition := range externalTransitions {
  101. if transition.From != "[*]" {
  102. r.renderTransition(&builder, transition)
  103. }
  104. }
  105. return builder.String(), nil
  106. }
  107. // sortStatesByTransitionOrder sorts states by their order in the transition chain
  108. func (r *StateRenderer) sortStatesByTransitionOrder(states []*ast.StateNode, transitions []*ast.StateTransition) {
  109. // For special states, sort by type priority: join -> fork -> choice -> others
  110. typePriority := map[ast.StateType]int{
  111. ast.StateTypeJoin: 0,
  112. ast.StateTypeFork: 1,
  113. ast.StateTypeChoice: 2,
  114. ast.StateTypeHistory: 3,
  115. ast.StateTypeDeepHistory: 4,
  116. ast.StateTypeDefault: 5,
  117. }
  118. // Sort states by type priority
  119. for i := 0; i < len(states); i++ {
  120. for j := i + 1; j < len(states); j++ {
  121. priorityI := typePriority[states[i].Type]
  122. priorityJ := typePriority[states[j].Type]
  123. if priorityI > priorityJ {
  124. states[i], states[j] = states[j], states[i]
  125. }
  126. }
  127. }
  128. }
  129. // renderTransition renders a single transition
  130. func (r *StateRenderer) renderTransition(builder *strings.Builder, transition *ast.StateTransition) {
  131. builder.WriteString(" ")
  132. builder.WriteString(transition.From)
  133. builder.WriteString(" --> ")
  134. builder.WriteString(transition.To)
  135. // Add transition decorations: label, [guard], /action
  136. var decorations []string
  137. if transition.Label != nil {
  138. decorations = append(decorations, *transition.Label)
  139. }
  140. if transition.Condition != nil {
  141. decorations = append(decorations, fmt.Sprintf("[%s]", *transition.Condition))
  142. }
  143. if transition.Action != nil {
  144. decorations = append(decorations, fmt.Sprintf("/ %s", *transition.Action))
  145. }
  146. if len(decorations) > 0 {
  147. builder.WriteString(" : ")
  148. builder.WriteString(strings.Join(decorations, " "))
  149. }
  150. builder.WriteString("\n")
  151. }
  152. // renderStateActions renders state actions without explicit state declaration
  153. func (r *StateRenderer) renderStateActions(builder *strings.Builder, state *ast.StateNode) {
  154. if state.EntryAction != nil {
  155. builder.WriteString(" ")
  156. builder.WriteString(state.ID)
  157. builder.WriteString(" : entry ")
  158. builder.WriteString(*state.EntryAction)
  159. builder.WriteString("\n")
  160. }
  161. if state.ExitAction != nil {
  162. builder.WriteString(" ")
  163. builder.WriteString(state.ID)
  164. builder.WriteString(" : exit ")
  165. builder.WriteString(*state.ExitAction)
  166. builder.WriteString("\n")
  167. }
  168. if state.DoAction != nil {
  169. builder.WriteString(" ")
  170. builder.WriteString(state.ID)
  171. builder.WriteString(" : do ")
  172. builder.WriteString(*state.DoAction)
  173. builder.WriteString("\n")
  174. }
  175. }
  176. // renderState renders a state with explicit declaration
  177. func (r *StateRenderer) renderState(builder *strings.Builder, state *ast.StateNode) {
  178. builder.WriteString(" state ")
  179. builder.WriteString(state.ID)
  180. // Add alias if different from ID
  181. if state.Label != state.ID {
  182. builder.WriteString(" as ")
  183. if strings.Contains(state.Label, " ") {
  184. builder.WriteString(fmt.Sprintf("\"%s\"", state.Label))
  185. } else {
  186. builder.WriteString(state.Label)
  187. }
  188. }
  189. // Add description or special type
  190. if state.Description != nil {
  191. builder.WriteString(" : ")
  192. builder.WriteString(*state.Description)
  193. } else {
  194. switch state.Type {
  195. case ast.StateTypeFork:
  196. builder.WriteString(" : <<fork>>")
  197. case ast.StateTypeJoin:
  198. builder.WriteString(" : <<join>>")
  199. case ast.StateTypeChoice:
  200. builder.WriteString(" : <<choice>>")
  201. case ast.StateTypeHistory:
  202. builder.WriteString(" : <<history>>")
  203. case ast.StateTypeDeepHistory:
  204. builder.WriteString(" : <<deepHistory>>")
  205. }
  206. }
  207. builder.WriteString("\n")
  208. // Render composite state body if it has sub-states
  209. if len(state.SubStates) > 0 {
  210. builder.WriteString(" state ")
  211. builder.WriteString(state.ID)
  212. builder.WriteString(" {\n")
  213. for _, subState := range state.SubStates {
  214. builder.WriteString(" state ")
  215. builder.WriteString(subState.ID)
  216. if subState.Label != subState.ID {
  217. builder.WriteString(" as ")
  218. builder.WriteString(subState.Label)
  219. }
  220. if subState.Description != nil {
  221. builder.WriteString(" : ")
  222. builder.WriteString(*subState.Description)
  223. }
  224. builder.WriteString("\n")
  225. }
  226. builder.WriteString(" }\n")
  227. }
  228. // Render note if present
  229. if state.Note != nil {
  230. builder.WriteString(" note ")
  231. builder.WriteString(string(state.Note.Position))
  232. builder.WriteString(" ")
  233. builder.WriteString(state.ID)
  234. builder.WriteString(" : ")
  235. builder.WriteString(state.Note.Text)
  236. builder.WriteString("\n")
  237. }
  238. // Render state actions
  239. r.renderStateActions(builder, state)
  240. }
  241. // isStateInComposite checks if a state ID is within a composite state
  242. func (r *StateRenderer) isStateInComposite(compositeState *ast.StateNode, stateID string) bool {
  243. // Don't consider the composite state itself as internal
  244. if stateID == compositeState.ID {
  245. return false
  246. }
  247. // Check if it's a direct substate
  248. if _, exists := compositeState.SubStates[stateID]; exists {
  249. return true
  250. }
  251. // Check if it's [*] (start/end states are considered internal to composite states)
  252. if stateID == "[*]" {
  253. return true
  254. }
  255. // Check if it's within any nested composite state
  256. for _, subState := range compositeState.SubStates {
  257. if len(subState.SubStates) > 0 {
  258. // This is a nested composite state, check recursively
  259. if r.isStateInComposite(subState, stateID) {
  260. return true
  261. }
  262. }
  263. }
  264. return false
  265. }
  266. // renderStateWithInternalTransitions renders a state with its internal transitions
  267. func (r *StateRenderer) renderStateWithInternalTransitions(builder *strings.Builder, state *ast.StateNode, internalTransitions []*ast.StateTransition) {
  268. // For composite states, only render the composite structure
  269. if len(state.SubStates) > 0 {
  270. builder.WriteString(" state ")
  271. builder.WriteString(state.ID)
  272. // Add alias if different from ID
  273. if state.Label != state.ID {
  274. builder.WriteString(" as ")
  275. if strings.Contains(state.Label, " ") {
  276. builder.WriteString(fmt.Sprintf("\"%s\"", state.Label))
  277. } else {
  278. builder.WriteString(state.Label)
  279. }
  280. }
  281. // Add description or special type
  282. if state.Description != nil {
  283. builder.WriteString(" : ")
  284. builder.WriteString(*state.Description)
  285. } else {
  286. switch state.Type {
  287. case ast.StateTypeFork:
  288. builder.WriteString(" : <<fork>>")
  289. case ast.StateTypeJoin:
  290. builder.WriteString(" : <<join>>")
  291. case ast.StateTypeChoice:
  292. builder.WriteString(" : <<choice>>")
  293. case ast.StateTypeHistory:
  294. builder.WriteString(" : <<history>>")
  295. case ast.StateTypeDeepHistory:
  296. builder.WriteString(" : <<deepHistory>>")
  297. }
  298. }
  299. builder.WriteString(" {\n")
  300. // Render transitions that belong to this composite state but not to nested composite states
  301. for _, transition := range internalTransitions {
  302. // Check if this transition belongs to a nested composite state
  303. belongsToNested := false
  304. for _, subState := range state.SubStates {
  305. if len(subState.SubStates) > 0 {
  306. // This is a nested composite state
  307. if r.isStateInComposite(subState, transition.From) && r.isStateInComposite(subState, transition.To) {
  308. belongsToNested = true
  309. break
  310. }
  311. }
  312. }
  313. if !belongsToNested {
  314. builder.WriteString(" ")
  315. builder.WriteString(transition.From)
  316. builder.WriteString(" --> ")
  317. builder.WriteString(transition.To)
  318. // Add transition decorations
  319. var decorations []string
  320. if transition.Label != nil {
  321. decorations = append(decorations, *transition.Label)
  322. }
  323. if transition.Condition != nil {
  324. decorations = append(decorations, fmt.Sprintf("[%s]", *transition.Condition))
  325. }
  326. if transition.Action != nil {
  327. decorations = append(decorations, fmt.Sprintf("/ %s", *transition.Action))
  328. }
  329. if len(decorations) > 0 {
  330. builder.WriteString(" : ")
  331. builder.WriteString(strings.Join(decorations, " "))
  332. }
  333. builder.WriteString("\n")
  334. }
  335. }
  336. // Render nested composite states (in original order)
  337. // Create ordered slice from map to ensure consistent ordering
  338. var nestedStates []*ast.StateNode
  339. for _, subState := range state.SubStates {
  340. if len(subState.SubStates) > 0 {
  341. nestedStates = append(nestedStates, subState)
  342. }
  343. }
  344. // Sort nested states by their ID to ensure consistent ordering
  345. for i := 0; i < len(nestedStates); i++ {
  346. for j := i + 1; j < len(nestedStates); j++ {
  347. if nestedStates[i].ID > nestedStates[j].ID {
  348. nestedStates[i], nestedStates[j] = nestedStates[j], nestedStates[i]
  349. }
  350. }
  351. }
  352. for _, subState := range nestedStates {
  353. // This is a nested composite state, render it
  354. builder.WriteString(" state ")
  355. builder.WriteString(subState.ID)
  356. // Add alias if different from ID
  357. if subState.Label != subState.ID {
  358. builder.WriteString(" as ")
  359. if strings.Contains(subState.Label, " ") {
  360. builder.WriteString(fmt.Sprintf("\"%s\"", subState.Label))
  361. } else {
  362. builder.WriteString(subState.Label)
  363. }
  364. }
  365. // Add description or special type
  366. if subState.Description != nil {
  367. builder.WriteString(" : ")
  368. builder.WriteString(*subState.Description)
  369. } else {
  370. switch subState.Type {
  371. case ast.StateTypeFork:
  372. builder.WriteString(" : <<fork>>")
  373. case ast.StateTypeJoin:
  374. builder.WriteString(" : <<join>>")
  375. case ast.StateTypeChoice:
  376. builder.WriteString(" : <<choice>>")
  377. case ast.StateTypeHistory:
  378. builder.WriteString(" : <<history>>")
  379. case ast.StateTypeDeepHistory:
  380. builder.WriteString(" : <<deepHistory>>")
  381. }
  382. }
  383. builder.WriteString(" {\n")
  384. // Render nested state transitions
  385. for _, nestedTransition := range internalTransitions {
  386. // Check if this transition is within the nested state
  387. if r.isStateInComposite(subState, nestedTransition.From) && r.isStateInComposite(subState, nestedTransition.To) {
  388. builder.WriteString(" ")
  389. builder.WriteString(nestedTransition.From)
  390. builder.WriteString(" --> ")
  391. builder.WriteString(nestedTransition.To)
  392. // Add transition decorations
  393. var decorations []string
  394. if nestedTransition.Label != nil {
  395. decorations = append(decorations, *nestedTransition.Label)
  396. }
  397. if nestedTransition.Condition != nil {
  398. decorations = append(decorations, fmt.Sprintf("[%s]", *nestedTransition.Condition))
  399. }
  400. if nestedTransition.Action != nil {
  401. decorations = append(decorations, fmt.Sprintf("/ %s", *nestedTransition.Action))
  402. }
  403. if len(decorations) > 0 {
  404. builder.WriteString(" : ")
  405. builder.WriteString(strings.Join(decorations, " "))
  406. }
  407. builder.WriteString("\n")
  408. }
  409. }
  410. builder.WriteString(" }\n")
  411. }
  412. builder.WriteString(" }\n")
  413. } else {
  414. // For non-composite states, render the state declaration
  415. builder.WriteString(" state ")
  416. builder.WriteString(state.ID)
  417. // Add alias if different from ID
  418. if state.Label != state.ID {
  419. builder.WriteString(" as ")
  420. if strings.Contains(state.Label, " ") {
  421. builder.WriteString(fmt.Sprintf("\"%s\"", state.Label))
  422. } else {
  423. builder.WriteString(state.Label)
  424. }
  425. }
  426. // Add description or special type
  427. if state.Description != nil {
  428. builder.WriteString(" : ")
  429. builder.WriteString(*state.Description)
  430. } else {
  431. switch state.Type {
  432. case ast.StateTypeFork:
  433. builder.WriteString(" : <<fork>>")
  434. case ast.StateTypeJoin:
  435. builder.WriteString(" : <<join>>")
  436. case ast.StateTypeChoice:
  437. builder.WriteString(" : <<choice>>")
  438. case ast.StateTypeHistory:
  439. builder.WriteString(" : <<history>>")
  440. case ast.StateTypeDeepHistory:
  441. builder.WriteString(" : <<deepHistory>>")
  442. }
  443. }
  444. builder.WriteString("\n")
  445. // Render note if present
  446. if state.Note != nil {
  447. builder.WriteString(" note ")
  448. builder.WriteString(string(state.Note.Position))
  449. builder.WriteString(" ")
  450. builder.WriteString(state.ID)
  451. builder.WriteString(" : ")
  452. builder.WriteString(state.Note.Text)
  453. builder.WriteString("\n")
  454. }
  455. // Render state actions
  456. r.renderStateActions(builder, state)
  457. }
  458. }