organization.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Package renderer provides Organization Chart rendering
  2. package renderer
  3. import (
  4. "fmt"
  5. "strings"
  6. "mermaid-go/pkg/ast"
  7. )
  8. // OrganizationRenderer implements Organization Chart rendering
  9. type OrganizationRenderer struct{}
  10. // NewOrganizationRenderer creates a new Organization renderer
  11. func NewOrganizationRenderer() *OrganizationRenderer {
  12. return &OrganizationRenderer{}
  13. }
  14. // Render renders an Organization Chart to mermaid syntax
  15. func (r *OrganizationRenderer) Render(diagram *ast.OrganizationDiagram) (string, error) {
  16. var result strings.Builder
  17. // Start with organization declaration
  18. result.WriteString("organization\n")
  19. // Add title if present
  20. if diagram.Title != nil {
  21. result.WriteString(fmt.Sprintf(" title %s\n", *diagram.Title))
  22. }
  23. // Render nodes in hierarchical order
  24. if diagram.Root != nil {
  25. r.renderNodeHierarchy(&result, diagram.Root, " ")
  26. } else {
  27. // Render all nodes if no clear hierarchy
  28. for _, node := range diagram.Nodes {
  29. if node.Parent == nil { // Root nodes
  30. r.renderNodeHierarchy(&result, node, " ")
  31. }
  32. }
  33. }
  34. return result.String(), nil
  35. }
  36. // renderNodeHierarchy renders a node and its children recursively
  37. func (r *OrganizationRenderer) renderNodeHierarchy(result *strings.Builder, node *ast.OrganizationNode, indent string) {
  38. // Render current node
  39. result.WriteString(fmt.Sprintf("%s%s", indent, node.ID))
  40. if node.Name != node.ID {
  41. result.WriteString(fmt.Sprintf("[%s]", node.Name))
  42. }
  43. // Render children
  44. if len(node.Children) > 0 {
  45. result.WriteString("\n")
  46. for _, child := range node.Children {
  47. // Render connection
  48. result.WriteString(fmt.Sprintf("%s%s --> %s", indent, node.ID, child.ID))
  49. if child.Name != child.ID {
  50. result.WriteString(fmt.Sprintf("[%s]", child.Name))
  51. }
  52. result.WriteString("\n")
  53. }
  54. // Recursively render children
  55. for _, child := range node.Children {
  56. if len(child.Children) > 0 {
  57. r.renderNodeHierarchy(result, child, indent)
  58. }
  59. }
  60. } else {
  61. result.WriteString("\n")
  62. }
  63. }