package tui import ( "fmt" "sort" "strings" "git.a-wan.net/alan/pipelines/internal/protocol" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" ) func outcomes(stage protocol.Stage) []string { keys := make([]string, 0, len(stage.Edges)) for key := range stage.Edges { keys = append(keys, key) } sort.Slice(keys, func(i, j int) bool { priority := func(k string) int { if k == "success" { return 0 } if k == "error" { return 2 } return 1 } if a, b := priority(keys[i]), priority(keys[j]); a != b { return a < b } return keys[i] < keys[j] }) return keys } func compactGraph(graph protocol.Graph) bool { edges := 0 for _, stage := range graph.Stages { edges += len(stage.Edges) } return len(graph.Stages) > 200 || edges > 500 } type graphPoint struct{ x, y int } type graphEdge struct { id int source, target, outcome, label string from, to, lane, x int left bool path []graphPoint topEntry bool bottomExit bool } type graphNode struct { key string x, y, width, height int } type graphLayout struct { nodes []graphNode edges []graphEdge nodeX, nodeWidth, width, height int positions map[string]int } func graphEdges(graph protocol.Graph) []graphEdge { index := map[string]int{protocol.SuccessEnd: len(graph.Stages), protocol.FailureEnd: len(graph.Stages) + 1} for i, s := range graph.Stages { index[s.Key] = i } var edges []graphEdge for i, stage := range graph.Stages { for _, outcome := range outcomes(stage) { label := outcome if outcome == "error" && stage.FallbackError { label += "*" } target := protocol.ResolveTarget(outcome, stage.Edges[outcome]) edges = append(edges, graphEdge{id: len(edges) + 1, source: stage.Key, target: target, outcome: outcome, label: label, left: index[target] <= i}) } } return edges } func graphStageRow(graph protocol.Graph, key string) int { if !compactGraph(graph) { return layoutGraph(graph).positions[key] } row := 0 for _, stage := range graph.Stages { if stage.Key == key { return row } row += len(stage.Edges) + 1 } return 0 } func renderGraph(graph protocol.Graph, selection ...string) []string { selected := "" if len(selection) > 0 { selected = selection[0] } return renderGraphAppearance(graph, selected, nil) } // A nil appearance is the normal definition view. Run views dim all nodes and // routes not present in the audit, without removing any definition branches. type graphAppearance struct { nodes map[string]bool routes map[graphRoute]bool labels map[string]string } func (a *graphAppearance) label(key string) string { if a != nil && a.labels[key] != "" { return a.labels[key] } return nodeLabel(key) } func layoutGraphAppearance(graph protocol.Graph, appearance *graphAppearance) graphLayout { if appearance == nil || len(appearance.labels) == 0 { return layoutGraph(graph) } display := protocol.Graph{} keys := map[string]string{} label := func(key string) string { if protocol.IsTerminal(key) { return key } return appearance.label(key) } for _, stage := range graph.Stages { copy := stage copy.Key = label(stage.Key) keys[copy.Key] = stage.Key copy.Edges = map[string]string{} for outcome, target := range stage.Edges { copy.Edges[outcome] = label(protocol.ResolveTarget(outcome, target)) } display.Stages = append(display.Stages, copy) } layout := layoutGraph(display) for i, node := range layout.nodes { if key, ok := keys[node.key]; ok { layout.nodes[i].key = key } } for i, edge := range layout.edges { if key, ok := keys[edge.source]; ok { layout.edges[i].source = key } if key, ok := keys[edge.target]; ok { layout.edges[i].target = key } } return layout } type graphRoute struct{ source, outcome, target string } func (a *graphAppearance) nodeColor(key string, graph protocol.Graph) lipgloss.Color { if a != nil && !a.nodes[key] { return themeMuted } return stageColor(key, graph) } func (a *graphAppearance) title(key, label string, selected bool, graph protocol.Graph) string { if a == nil { return stageTitle(key, label, selected, graph) } s := lipgloss.NewStyle().Foreground(a.nodeColor(key, graph)).Bold(a.nodes[key]) if selected { s = s.Background(themeSelection) } return s.Render(label) } func (a *graphAppearance) edgeStyle(edge graphEdge) (lipgloss.Color, bool) { if a != nil && !a.routes[graphRoute{edge.source, edge.outcome, edge.target}] { return themeMuted, false } return outcomeColor(edge.outcome), true } func renderGraphAppearance(graph protocol.Graph, selected string, appearance *graphAppearance) []string { if len(graph.Stages) == 0 { return []string{"(empty graph)"} } if compactGraph(graph) { var lines []string edges, index := graphEdges(graph), 0 for _, stage := range graph.Stages { lines = append(lines, appearance.title(stage.Key, "["+appearance.label(stage.Key)+"]", stage.Key == selected, graph)) for range outcomes(stage) { e := edges[index] index++ color, bold := appearance.edgeStyle(e) label := lipgloss.NewStyle().Foreground(color).Bold(bold).Render(fmt.Sprintf("└─ %s [%d] → ", e.label, e.id)) lines = append(lines, " "+label+appearance.title(e.target, "["+nodeLabel(e.target)+"]", false, graph)) } } return append(lines, appearance.title(protocol.FailureEnd, "[FAILURE]", false, graph)+" "+appearance.title(protocol.SuccessEnd, "[SUCCESS]", false, graph)) } layout := layoutGraphAppearance(graph, appearance) type cell struct { glyph rune color lipgloss.Color bold bool } canvas := make([][]cell, layout.height) for row := range canvas { canvas[row] = make([]cell, layout.width) for x := range canvas[row] { canvas[row][x].glyph = ' ' } } put := func(x, y int, r rune, color lipgloss.Color, bold bool) { canvas[y][x] = cell{r, color, bold} } text := func(x, y int, s string, color lipgloss.Color, bold bool) { for _, r := range s { put(x, y, r, color, bold) x++ } } nodes := map[string]graphNode{} for _, node := range layout.nodes { nodes[node.key] = node x, w, y, h := node.x, node.width, node.y, node.height color := appearance.nodeColor(node.key, graph) active := node.key == selected top, bottom, vertical := "╭"+strings.Repeat("─", w-2)+"╮", "╰"+strings.Repeat("─", w-2)+"╯", '│' if active { top = "╔" + strings.Repeat("═", w-2) + "╗" bottom = "╚" + strings.Repeat("═", w-2) + "╝" vertical = '║' } text(x, y, top, color, active) for row := y + 1; row < y+h-1; row++ { put(x, row, vertical, color, active) put(x+w-1, row, vertical, color, active) } text(x, y+h-1, bottom, color, active) } line := func(p graphPoint, r rune, color lipgloss.Color) { // Edges are drawn in stable ID order. The earlier route stays intact at // every crossing, including its color; never invent a joining glyph. if canvas[p.y][p.x].glyph == ' ' { put(p.x, p.y, r, color, false) } } for _, edge := range layout.edges { color, bold := appearance.edgeStyle(edge) path := []graphPoint{} for i := 1; i < len(edge.path); i++ { a, b := edge.path[i-1], edge.path[i] dx, dy := 0, 0 if b.x > a.x { dx = 1 } else if b.x < a.x { dx = -1 } if b.y > a.y { dy = 1 } else if b.y < a.y { dy = -1 } if len(path) == 0 { path = append(path, a) } for a != b { a.x += dx a.y += dy path = append(path, a) } } for i := 1; i < len(path)-1; i++ { p, a, b := path[i], path[i-1], path[i+1] glyph := '─' if a.x == b.x { glyph = '│' } else if a.y != b.y { left, right, up, down := a.x < p.x || b.x < p.x, a.x > p.x || b.x > p.x, a.y < p.y || b.y < p.y, a.y > p.y || b.y > p.y switch { case right && down: glyph = '┌' case left && down: glyph = '┐' case right && up: glyph = '└' case left && up: glyph = '┘' } } line(p, glyph, color) } start, end := path[0], path[len(path)-1] if edge.bottomExit { put(start.x, start.y, '▼', color, bold) } else { put(start.x, start.y, '├', color, false) put(start.x+1, start.y, '→', color, false) } if edge.topEntry { put(end.x, end.y, '▼', color, bold) text(end.x-1, end.y-1, fmt.Sprintf("[%d]", edge.id), color, bold) } else { put(end.x, end.y, '▶', color, bold) target := nodes[edge.target] text(target.x+2, edge.to, fmt.Sprintf("[%d]", edge.id), color, bold) } source := nodes[edge.source] label := fmt.Sprintf("%s [%d]", edge.label, edge.id) text(source.x+source.width-2-len(label), edge.from, label, color, bold) } result := make([]string, layout.height) for row, cells := range canvas { var b strings.Builder end := len(cells) for end > 0 && cells[end-1].glyph == ' ' { end-- } for x := 0; x < end; { current, next := cells[x], x+1 for next < end && cells[next].color == current.color && cells[next].bold == current.bold { next++ } var run strings.Builder for i := x; i < next; i++ { run.WriteRune(cells[i].glyph) } style := lipgloss.NewStyle().Bold(current.bold) if current.color != "" { style = style.Foreground(current.color) } b.WriteString(style.Render(run.String())) x = next } result[row] = b.String() } for _, node := range layout.nodes { label, row := appearance.label(node.key), node.y+1 left := ansi.Cut(result[row], 0, node.x+1) title := " " + label + strings.Repeat(" ", node.width-3-ansi.StringWidth(label)) right := ansi.Cut(result[row], node.x+node.width-1, layout.width) result[row] = left + appearance.title(node.key, title, node.key == selected, graph) + right } return result }