sessions_item.go

  1package dialog
  2
  3import (
  4	"strings"
  5	"time"
  6
  7	"charm.land/lipgloss/v2"
  8	"github.com/charmbracelet/crush/internal/session"
  9	"github.com/charmbracelet/crush/internal/ui/list"
 10	"github.com/charmbracelet/crush/internal/ui/styles"
 11	"github.com/charmbracelet/x/ansi"
 12	"github.com/dustin/go-humanize"
 13	"github.com/rivo/uniseg"
 14	"github.com/sahilm/fuzzy"
 15)
 16
 17// ListItem represents a selectable and searchable item in a dialog list.
 18type ListItem interface {
 19	list.FilterableItem
 20	list.Focusable
 21	list.MatchSettable
 22
 23	// ID returns the unique identifier of the item.
 24	ID() string
 25}
 26
 27// SessionItem wraps a [session.Session] to implement the [ListItem] interface.
 28type SessionItem struct {
 29	session.Session
 30	t       *styles.Styles
 31	m       fuzzy.Match
 32	cache   map[int]string
 33	focused bool
 34}
 35
 36var _ ListItem = &SessionItem{}
 37
 38// Filter returns the filterable value of the session.
 39func (s *SessionItem) Filter() string {
 40	return s.Title
 41}
 42
 43// ID returns the unique identifier of the session.
 44func (s *SessionItem) ID() string {
 45	return s.Session.ID
 46}
 47
 48// SetMatch sets the fuzzy match for the session item.
 49func (s *SessionItem) SetMatch(m fuzzy.Match) {
 50	s.cache = nil
 51	s.m = m
 52}
 53
 54// Render returns the string representation of the session item.
 55func (s *SessionItem) Render(width int) string {
 56	return renderItem(s.t, s.Title, s.UpdatedAt, s.focused, width, s.cache, &s.m)
 57}
 58
 59func renderItem(t *styles.Styles, title string, updatedAt int64, focused bool, width int, cache map[int]string, m *fuzzy.Match) string {
 60	if cache == nil {
 61		cache = make(map[int]string)
 62	}
 63
 64	cached, ok := cache[width]
 65	if ok {
 66		return cached
 67	}
 68
 69	style := t.Dialog.NormalItem
 70	if focused {
 71		style = t.Dialog.SelectedItem
 72	}
 73
 74	width -= style.GetHorizontalFrameSize()
 75
 76	var age string
 77	if updatedAt > 0 {
 78		age = humanize.Time(time.Unix(updatedAt, 0))
 79		if focused {
 80			age = t.Base.Render(age)
 81		} else {
 82			age = t.Subtle.Render(age)
 83		}
 84
 85		age = " " + age
 86	}
 87
 88	var ageLen int
 89	if updatedAt > 0 {
 90		ageLen = lipgloss.Width(age)
 91	}
 92
 93	title = ansi.Truncate(title, max(0, width-ageLen), "…")
 94	titleLen := lipgloss.Width(title)
 95	right := lipgloss.NewStyle().AlignHorizontal(lipgloss.Right).Width(width - titleLen).Render(age)
 96	content := title
 97	if matches := len(m.MatchedIndexes); matches > 0 {
 98		var lastPos int
 99		parts := make([]string, 0)
100		ranges := matchedRanges(m.MatchedIndexes)
101		for _, rng := range ranges {
102			start, stop := bytePosToVisibleCharPos(title, rng)
103			if start > lastPos {
104				parts = append(parts, title[lastPos:start])
105			}
106			// NOTE: We're using [ansi.Style] here instead of [lipglosStyle]
107			// because we can control the underline start and stop more
108			// precisely via [ansi.AttrUnderline] and [ansi.AttrNoUnderline]
109			// which only affect the underline attribute without interfering
110			// with other style
111			parts = append(parts,
112				ansi.NewStyle().Underline(true).String(),
113				title[start:stop+1],
114				ansi.NewStyle().Underline(false).String(),
115			)
116			lastPos = stop + 1
117		}
118		if lastPos < len(title) {
119			parts = append(parts, title[lastPos:])
120		}
121
122		content = strings.Join(parts, "")
123	}
124
125	content = style.Render(content + right)
126	cache[width] = content
127	return content
128}
129
130// SetFocused sets the focus state of the session item.
131func (s *SessionItem) SetFocused(focused bool) {
132	if s.focused != focused {
133		s.cache = nil
134	}
135	s.focused = focused
136}
137
138// sessionItems takes a slice of [session.Session]s and convert them to a slice
139// of [ListItem]s.
140func sessionItems(t *styles.Styles, sessions ...session.Session) []list.FilterableItem {
141	items := make([]list.FilterableItem, len(sessions))
142	for i, s := range sessions {
143		items[i] = &SessionItem{Session: s, t: t}
144	}
145	return items
146}
147
148func matchedRanges(in []int) [][2]int {
149	if len(in) == 0 {
150		return [][2]int{}
151	}
152	current := [2]int{in[0], in[0]}
153	if len(in) == 1 {
154		return [][2]int{current}
155	}
156	var out [][2]int
157	for i := 1; i < len(in); i++ {
158		if in[i] == current[1]+1 {
159			current[1] = in[i]
160		} else {
161			out = append(out, current)
162			current = [2]int{in[i], in[i]}
163		}
164	}
165	out = append(out, current)
166	return out
167}
168
169func bytePosToVisibleCharPos(str string, rng [2]int) (int, int) {
170	bytePos, byteStart, byteStop := 0, rng[0], rng[1]
171	pos, start, stop := 0, 0, 0
172	gr := uniseg.NewGraphemes(str)
173	for byteStart > bytePos {
174		if !gr.Next() {
175			break
176		}
177		bytePos += len(gr.Str())
178		pos += max(1, gr.Width())
179	}
180	start = pos
181	for byteStop > bytePos {
182		if !gr.Next() {
183			break
184		}
185		bytePos += len(gr.Str())
186		pos += max(1, gr.Width())
187	}
188	stop = pos
189	return start, stop
190}