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.Session.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.Session.Title, s.Session.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 ageLen := lipgloss.Width(age)
88 titleLen := lipgloss.Width(title)
89 title = ansi.Truncate(title, max(0, width-ageLen), "…")
90 right := lipgloss.NewStyle().AlignHorizontal(lipgloss.Right).Width(width - titleLen).Render(age)
91
92 content := title
93 if matches := len(m.MatchedIndexes); matches > 0 {
94 var lastPos int
95 parts := make([]string, 0)
96 ranges := matchedRanges(m.MatchedIndexes)
97 for _, rng := range ranges {
98 start, stop := bytePosToVisibleCharPos(title, rng)
99 if start > lastPos {
100 parts = append(parts, title[lastPos:start])
101 }
102 // NOTE: We're using [ansi.Style] here instead of [lipglosStyle]
103 // because we can control the underline start and stop more
104 // precisely via [ansi.AttrUnderline] and [ansi.AttrNoUnderline]
105 // which only affect the underline attribute without interfering
106 // with other style
107 parts = append(parts,
108 ansi.NewStyle().Underline(true).String(),
109 title[start:stop+1],
110 ansi.NewStyle().Underline(false).String(),
111 )
112 lastPos = stop + 1
113 }
114 if lastPos < len(title) {
115 parts = append(parts, title[lastPos:])
116 }
117
118 content = strings.Join(parts, "")
119 }
120
121 content = style.Render(content + right)
122 cache[width] = content
123 return content
124}
125
126// SetFocused sets the focus state of the session item.
127func (s *SessionItem) SetFocused(focused bool) {
128 if s.focused != focused {
129 s.cache = nil
130 }
131 s.focused = focused
132}
133
134// sessionItems takes a slice of [session.Session]s and convert them to a slice
135// of [ListItem]s.
136func sessionItems(t *styles.Styles, sessions ...session.Session) []list.FilterableItem {
137 items := make([]list.FilterableItem, len(sessions))
138 for i, s := range sessions {
139 items[i] = &SessionItem{Session: s, t: t}
140 }
141 return items
142}
143
144func matchedRanges(in []int) [][2]int {
145 if len(in) == 0 {
146 return [][2]int{}
147 }
148 current := [2]int{in[0], in[0]}
149 if len(in) == 1 {
150 return [][2]int{current}
151 }
152 var out [][2]int
153 for i := 1; i < len(in); i++ {
154 if in[i] == current[1]+1 {
155 current[1] = in[i]
156 } else {
157 out = append(out, current)
158 current = [2]int{in[i], in[i]}
159 }
160 }
161 out = append(out, current)
162 return out
163}
164
165func bytePosToVisibleCharPos(str string, rng [2]int) (int, int) {
166 bytePos, byteStart, byteStop := 0, rng[0], rng[1]
167 pos, start, stop := 0, 0, 0
168 gr := uniseg.NewGraphemes(str)
169 for byteStart > bytePos {
170 if !gr.Next() {
171 break
172 }
173 bytePos += len(gr.Str())
174 pos += max(1, gr.Width())
175 }
176 start = pos
177 for byteStop > bytePos {
178 if !gr.Next() {
179 break
180 }
181 bytePos += len(gr.Str())
182 pos += max(1, gr.Width())
183 }
184 stop = pos
185 return start, stop
186}