Files
pipelines/internal/tui/dashboard.go
T

345 lines
9.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package tui
import (
"fmt"
"strconv"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"github.com/sahilm/fuzzy"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
var commands = []string{":status", ":logs", ":new", ":drafts", ":templates", ":refresh", ":ping", ":edit", ":submit", ":versions", ":run", ":runs", ":retry", ":debug", ":pipeline", ":home", ":quit"}
func (m Model) footerContent() string {
label := fmt.Sprintf(" LOGS %d · :logs ", len(m.lines))
style := lipgloss.NewStyle().Foreground(themeMuted)
if m.unread > 0 {
label = fmt.Sprintf(" ● %d NEW · LOGS %d · :logs ", m.unread, len(m.lines))
if m.width < 60 {
label = fmt.Sprintf(" ● %d NEW · :logs ", m.unread)
}
style = lipgloss.NewStyle().Foreground(themeAccent).Bold(true).Reverse(true)
} else if len(m.lines) > 0 {
style = lipgloss.NewStyle().Foreground(themeAccent).Bold(true)
}
label = style.Render(ansi.Truncate(label, m.width, ""))
available := m.width - lipgloss.Width(label) - 1
left := ""
if available > 0 {
keys := m.keys
keys.retryAvailable = m.selectedFailedRun() > 0
left = ansi.Truncate(m.help.View(keys), available, "…")
}
return left + strings.Repeat(" ", max(0, m.width-lipgloss.Width(left)-lipgloss.Width(label))) + label
}
func (m Model) homeLines() []string {
panelWidth := m.width
if m.width >= 96 {
panelWidth = (m.width - 1) / 2
}
runs := []string{bar("Latest runs", fmt.Sprint(len(m.runs)), max(1, panelWidth-4), true),
"r all runs · :status server & ntfy",
lipgloss.NewStyle().Foreground(themeMuted).Render("Pipeline · Version · Outcome · Duration"),
"Inspect with :runs; use :run in a pipeline."}
if len(m.runs) == 0 {
runs = append(runs, "No runs yet.")
}
for _, r := range m.runs[:min(8, len(m.runs))] {
runs = append(runs, fmt.Sprintf("#%d %s · v%d · %s · %s", r.ID, r.Name, r.Version, m.progress(r.Status), runDuration(r.CreatedAt, r.FinishedAt)), " Started: "+dateLabel(r.CreatedAt))
if r.CurrentStage != "" && (r.Status == "running" || r.Status == "queued") {
runs = append(runs, " Stage: "+r.CurrentStage)
}
}
if len(m.runs) > 8 {
runs = append(runs, "More runs: r or :runs (latest 50)")
}
lines := []string{bar("Existing pipelines", fmt.Sprintf("%d", len(m.pipelines)), max(1, panelWidth-4), true), "r all runs · / search · n new", ""}
if !m.loaded {
lines = append(lines, "Waiting for pipeline data…")
} else if len(m.pipelines) == 0 {
lines = append(lines, "No pipelines yet. Press b for templates, d for drafts, or n to create one.")
} else {
for _, p := range m.pipelines {
lines = append(lines,
fmt.Sprintf("%s v%d · %d stages", p.Name, p.Version, p.Stages),
" Created: "+dateLabel(p.CreatedAt), " Updated: "+dateLabel(p.UpdatedAt))
if m.usage != nil {
for _, u := range m.usage.Pipelines {
if u.PipelineID == p.ID {
lines = append(lines, fmt.Sprintf(" %d runs · %s · avg %s", u.Total, successLabel(u.RunCounts), averageLabel(u.RunCounts)))
break
}
}
}
}
}
if m.width < 8 {
return append(append(runs, ""), lines...)
}
widget := func(rows []string, width int) string {
for i := range rows {
rows[i] = ansi.Truncate(rows[i], max(1, width-4), "…")
}
content := lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).
BorderForeground(themeMuted).Padding(0, 1).Width(width - 2).
Render(strings.Join(rows, "\n"))
return content
}
panels := widget(runs, panelWidth) + "\n\n" + widget(lines, panelWidth)
if m.width >= 96 {
panels = lipgloss.JoinHorizontal(lipgloss.Top, widget(runs, panelWidth), " ", widget(lines, m.width-panelWidth-1))
}
return strings.Split(widget(m.usageLines(), m.width)+"\n"+panels, "\n")
}
func (m Model) homePage() bool {
return !m.keys.detail && !m.runOpen && !m.templateOpen && !m.draftOpen && m.runForm == 0
}
func (m Model) pageCommands() []string {
available := []string{}
detailPage := m.keys.detail && !m.runOpen
for _, command := range commands {
switch command {
case ":debug":
if m.selectedRunID() <= 0 {
continue
}
case ":retry":
if m.selectedFailedRun() <= 0 {
continue
}
case ":pipeline":
if id, version := m.selectedRunPipeline(); id <= 0 || version <= 0 {
continue
}
case ":new", ":ping", ":templates":
if !m.homePage() {
continue
}
case ":edit", ":versions", ":run":
if !detailPage || m.detail == nil || m.detailLoading {
continue
}
case ":submit":
if !detailPage || m.pendingDraft == nil {
continue
}
case ":home":
if m.homePage() {
continue
}
}
available = append(available, command)
}
return available
}
func (m Model) matches() []string {
available := m.pageCommands()
query := strings.TrimPrefix(strings.TrimSpace(m.commandInput.Value()), ":")
if query == "" {
return available
}
result := []string{}
for _, match := range fuzzy.Find(query, available) {
result = append(result, match.Str)
}
return result
}
func (m Model) updatePalette(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.searchOpen {
return m.updateSearch(msg)
}
items := m.matches()
switch msg.String() {
case "esc":
m.paletteOpen = false
m.keys.palette = false
return m, nil
case "down", "ctrl+n":
m.commandIndex = min(m.commandIndex+1, max(0, len(items)-1))
return m, nil
case "up", "ctrl+p":
m.commandIndex = max(0, m.commandIndex-1)
return m, nil
case "enter":
if len(items) == 0 {
return m, nil
}
command := items[min(m.commandIndex, len(items)-1)]
m.paletteOpen = false
m.keys.palette = false
switch command {
case ":status":
return m.openStatus()
case ":debug":
return m.debugRun()
case ":retry":
return m.retrySelectedRun()
case ":pipeline":
return m.openRunPipeline()
case ":drafts":
return m.openDrafts()
case ":templates":
return m.openTemplates()
case ":run":
return m.beginRun()
case ":runs":
m.runFailedOnly = false
m.runPipelineID = 0
m.runOpen = true
m.keys.runs = true
m.runDetail = nil
m.requestedRunID = 0
m.runStartRequest = ""
m.runError = ""
m.runTop = 0
return m.runRequest(protocol.Message{Type: protocol.ListRuns})
case ":logs":
m.logOpen = true
m.keys.logs = true
m.logTop = max(0, len(m.lines)-m.logPageSize())
m.markVisibleLogs()
return m, nil
case ":new":
return m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
case ":ping":
return m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'t'}})
case ":quit":
return m, tea.Quit
case ":edit":
return m.editPipeline()
case ":submit":
if m.pendingDraft != nil {
m.confirmOpen = true
m.keys.confirm = true
} else {
m.appendLine("no edited draft to submit")
}
return m, nil
case ":versions":
return m.openVersions()
case ":home":
m.closeRuns()
return m.goHome(), nil
case ":refresh":
if m.runOpen {
request := protocol.Message{Type: protocol.ListRuns}
if m.requestedRunID > 0 {
request.Type = protocol.GetRun
request.RunID = m.requestedRunID
}
return m.runRequest(request)
}
if m.detail != nil && m.keys.detail {
return m.requestPipeline(m.detail.ID, m.detail.Version)
}
if m.conn == nil {
m.appendLine("not connected")
return m, nil
}
m.nextID++
return m, m.send(protocol.Message{Type: protocol.List, ID: strconv.FormatUint(m.nextID, 10)})
}
}
var cmd tea.Cmd
m.commandInput, cmd = m.commandInput.Update(msg)
m.commandIndex = 0
return m, cmd
}
// The popup reserves two lines for its border and two for title/separation.
func (m Model) logPageSize() int { return max(0, min(24, m.height-8)) }
func (m *Model) markVisibleLogs() {
for i := m.logTop; i < min(len(m.lines), m.logTop+m.logPageSize()); i++ {
if !m.logSeen[i] {
m.logSeen[i] = true
m.unread--
}
}
}
func (m Model) updateLogs(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc", "q":
m.logOpen = false
m.keys.logs = false
return m, nil
case "j", "down":
m.logTop++
case "k", "up":
m.logTop--
case "h":
m.logTop -= max(1, m.logPageSize()/2)
case "l":
m.logTop += max(1, m.logPageSize()/2)
}
m.logTop = max(0, min(m.logTop, max(0, len(m.lines)-m.logPageSize())))
m.markVisibleLogs()
return m, nil
}
func popup(width, height, preferredWidth int, lines []string) string {
inner := min(preferredWidth, max(1, width-6))
for i := range lines {
lines[i] = ansi.Truncate(lines[i], inner, "…")
}
if len(lines) > 0 {
lines[0] = bar(lines[0], "", inner, true)
}
dialog := lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).
BorderForeground(themeAccent).Padding(0, 1).Width(inner + 2).
Render(strings.Join(lines, "\n"))
if lipgloss.Width(dialog) > width || lipgloss.Height(dialog) > height {
lines = lines[:min(len(lines), height)]
for i := range lines {
lines[i] = ansi.Truncate(lines[i], width, "…")
}
dialog = strings.Join(lines, "\n")
}
return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, dialog)
}
func (m Model) logsView(height int) string {
end := min(len(m.lines), m.logTop+m.logPageSize())
lines := []string{fmt.Sprintf("Logs · %d–%d / %d", min(m.logTop+1, len(m.lines)), end, len(m.lines)), ""}
if len(m.lines) == 0 {
lines = append(lines, "No logs yet.")
} else {
lines = append(lines, m.lines[m.logTop:end]...)
}
return popup(m.width, height, 100, lines)
}
func (m Model) paletteView(height int) string {
if m.searchOpen {
return m.searchView(height)
}
field := m.commandInput
field.Width = max(1, min(48, m.width-10))
lines := []string{"Commands", field.View(), ""}
items := m.matches()
if len(items) == 0 {
lines = append(lines, "No matching commands")
}
start, end := selectionWindow(len(items), m.commandIndex, max(1, height-5))
for i := start; i < end; i++ {
item := items[i]
prefix := " "
if i == m.commandIndex {
prefix = "› "
}
lines = append(lines, menuOption(prefix+item, i == m.commandIndex))
}
return popup(m.width, height, 54, lines)
}