refsitem.go

 1package repo
 2
 3import (
 4	"fmt"
 5	"io"
 6
 7	"github.com/charmbracelet/bubbles/list"
 8	tea "github.com/charmbracelet/bubbletea"
 9	"github.com/charmbracelet/soft-serve/git"
10	"github.com/charmbracelet/soft-serve/tui/common"
11	"github.com/charmbracelet/soft-serve/ui/styles"
12)
13
14// RefItem is a git reference item.
15type RefItem struct {
16	*git.Reference
17}
18
19// ID implements selector.IdentifiableItem.
20func (i RefItem) ID() string {
21	return i.Reference.Name().String()
22}
23
24// Title implements list.DefaultItem.
25func (i RefItem) Title() string {
26	return i.Reference.Name().Short()
27}
28
29// Description implements list.DefaultItem.
30func (i RefItem) Description() string {
31	return ""
32}
33
34// Short returns the short name of the reference.
35func (i RefItem) Short() string {
36	return i.Reference.Name().Short()
37}
38
39// FilterValue implements list.Item.
40func (i RefItem) FilterValue() string { return i.Short() }
41
42// RefItems is a list of git references.
43type RefItems []RefItem
44
45// Len implements sort.Interface.
46func (cl RefItems) Len() int { return len(cl) }
47
48// Swap implements sort.Interface.
49func (cl RefItems) Swap(i, j int) { cl[i], cl[j] = cl[j], cl[i] }
50
51// Less implements sort.Interface.
52func (cl RefItems) Less(i, j int) bool {
53	return cl[i].Short() < cl[j].Short()
54}
55
56// RefItemDelegate is the delegate for the ref item.
57type RefItemDelegate struct {
58	style *styles.Styles
59}
60
61// Height implements list.ItemDelegate.
62func (d RefItemDelegate) Height() int { return 1 }
63
64// Spacing implements list.ItemDelegate.
65func (d RefItemDelegate) Spacing() int { return 0 }
66
67// Update implements list.ItemDelegate.
68func (d RefItemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd { return nil }
69
70// Render implements list.ItemDelegate.
71func (d RefItemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
72	s := d.style
73	i, ok := listItem.(RefItem)
74	if !ok {
75		return
76	}
77
78	ref := i.Short()
79	if i.Reference.IsTag() {
80		ref = s.RefItemTag.Render(ref)
81	}
82	ref = s.RefItemBranch.Render(ref)
83	refMaxWidth := m.Width() -
84		s.RefItemSelector.GetMarginLeft() -
85		s.RefItemSelector.GetWidth() -
86		s.RefItemInactive.GetMarginLeft()
87	ref = common.TruncateString(ref, refMaxWidth, "…")
88	if index == m.Index() {
89		fmt.Fprint(w, s.RefItemSelector.Render(">")+
90			s.RefItemActive.Render(ref))
91	} else {
92		fmt.Fprint(w, s.LogItemSelector.Render(" ")+
93			s.RefItemInactive.Render(ref))
94	}
95}