bubble.go

 1package commits
 2
 3import (
 4	"strings"
 5
 6	"github.com/charmbracelet/bubbles/viewport"
 7	tea "github.com/charmbracelet/bubbletea"
 8	"github.com/charmbracelet/soft/internal/git"
 9	"github.com/dustin/go-humanize"
10)
11
12type Bubble struct {
13	Commits  []git.RepoCommit
14	Height   int
15	Width    int
16	viewport viewport.Model
17}
18
19func NewBubble(height int, width int, rcs []git.RepoCommit) *Bubble {
20	b := &Bubble{
21		Commits:  rcs,
22		viewport: viewport.Model{Height: height, Width: width},
23	}
24	s := ""
25	for _, rc := range rcs {
26		s += b.renderCommit(rc) + "\n"
27	}
28	b.viewport.SetContent(s)
29	return b
30}
31
32func (b *Bubble) Init() tea.Cmd {
33	return nil
34}
35
36func (b *Bubble) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
37	cmds := make([]tea.Cmd, 0)
38	switch msg := msg.(type) {
39	case tea.KeyMsg:
40		switch msg.String() {
41		case "up", "k":
42			b.viewport.LineUp(1)
43		case "down", "j":
44			b.viewport.LineDown(1)
45		}
46	}
47	return b, tea.Batch(cmds...)
48}
49
50func (b *Bubble) renderCommit(rc git.RepoCommit) string {
51	s := ""
52	s += commitRepoNameStyle.Render(rc.Name)
53	s += " "
54	s += commitDateStyle.Render(humanize.Time(rc.Commit.Author.When))
55	s += "\n"
56	s += commitCommentStyle.Render(strings.TrimSpace(rc.Commit.Message))
57	s += "\n"
58	s += commitAuthorStyle.Render(rc.Commit.Author.Name)
59	s += " "
60	s += commitAuthorEmailStyle.Render(rc.Commit.Author.Email)
61	s += " "
62	return commitBoxStyle.Width(b.viewport.Width).Render(s)
63}
64
65func (b *Bubble) View() string {
66	return b.viewport.View()
67}