buildr/internal/tui/pager.go
Peter 1261932bdc
All checks were successful
continuous-integration/drone/push Build is passing
refactor: apply golangci-lint findings
2023-06-22 19:16:00 +02:00

118 lines
2.7 KiB
Go

package tui
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var (
_ tea.Model = (*Pager)(nil)
titleStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Right = "├"
return lipgloss.NewStyle().BorderStyle(b).Padding(0, 1)
}()
infoStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Left = "┤"
return titleStyle.Copy().BorderStyle(b)
}()
)
func NewPager(title, content string) *Pager {
return &Pager{
title: title,
content: content,
}
}
type Pager struct {
title string
content string
viewport viewport.Model
ready bool
}
func (p *Pager) Init() tea.Cmd {
return nil
}
func (p *Pager) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
switch msg := msg.(type) {
case tea.KeyMsg:
if k := msg.String(); k == "ctrl+c" || k == "q" || k == "esc" {
return p, tea.Quit
}
case tea.WindowSizeMsg:
headerHeight := lipgloss.Height(p.headerView())
footerHeight := lipgloss.Height(p.footerView())
verticalMarginHeight := headerHeight + footerHeight
if !p.ready {
// Since this program is using the full size of the viewport we
// need to wait until we've received the window dimensions before
// we can initialize the viewport. The initial dimensions come in
// quickly, though asynchronously, which is why we wait for them
// here.
p.viewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)
p.viewport.YPosition = headerHeight
p.viewport.SetContent(p.content)
p.ready = true
} else {
p.viewport.Width = msg.Width
p.viewport.Height = msg.Height - verticalMarginHeight
}
}
// Handle keyboard and mouse events in the viewport
p.viewport, cmd = p.viewport.Update(msg)
cmds = append(cmds, cmd)
return p, tea.Batch(cmds...)
}
func (p *Pager) View() string {
if !p.ready {
return "\n Initializing..."
}
builder := new(strings.Builder)
builder.WriteString(p.headerView())
builder.WriteString(p.viewport.View())
builder.WriteString(p.footerView())
return builder.String()
}
func (p *Pager) headerView() string {
title := titleStyle.Render(p.title)
line := strings.Repeat("─", max(0, p.viewport.Width-lipgloss.Width(title)))
return lipgloss.JoinHorizontal(lipgloss.Center, title, line)
}
func (p *Pager) footerView() string {
const percentagePoints = 100
info := infoStyle.Render(fmt.Sprintf("%3.f%%", p.viewport.ScrollPercent()*percentagePoints))
line := strings.Repeat("─", max(0, p.viewport.Width-lipgloss.Width(info)))
return lipgloss.JoinHorizontal(lipgloss.Center, line, info)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}