1package dialog
2
3import (
4 "fmt"
5 "strings"
6 "time"
7
8 "charm.land/bubbles/v2/textinput"
9 tea "charm.land/bubbletea/v2"
10 "charm.land/lipgloss/v2"
11 "github.com/charmbracelet/crush/internal/session"
12 "github.com/charmbracelet/crush/internal/ui/list"
13 "github.com/charmbracelet/crush/internal/ui/styles"
14 "github.com/charmbracelet/x/ansi"
15 "github.com/dustin/go-humanize"
16 "github.com/rivo/uniseg"
17 "github.com/sahilm/fuzzy"
18)
19
20// ListItem represents a selectable and searchable item in a dialog list.
21type ListItem interface {
22 list.FilterableItem
23 list.Focusable
24 list.MatchSettable
25
26 // ID returns the unique identifier of the item.
27 ID() string
28}
29
30// SessionItem wraps a [session.Session] to implement the [ListItem] interface.
31type SessionItem struct {
32 session.Session
33 t *styles.Styles
34 sessionsMode sessionsMode
35 m fuzzy.Match
36 cache map[int]string
37 updateTitleInput textinput.Model
38 focused bool
39}
40
41var _ ListItem = &SessionItem{}
42
43// Filter returns the filterable value of the session.
44func (s *SessionItem) Filter() string {
45 return s.Title
46}
47
48// ID returns the unique identifier of the session.
49func (s *SessionItem) ID() string {
50 return s.Session.ID
51}
52
53// SetMatch sets the fuzzy match for the session item.
54func (s *SessionItem) SetMatch(m fuzzy.Match) {
55 s.cache = nil
56 s.m = m
57}
58
59// InputValue returns the updated title value
60func (s *SessionItem) InputValue() string {
61 return s.updateTitleInput.Value()
62}
63
64// HandleInput forwards input message to the update title input
65func (s *SessionItem) HandleInput(msg tea.Msg) tea.Cmd {
66 var cmd tea.Cmd
67 s.updateTitleInput, cmd = s.updateTitleInput.Update(msg)
68 return cmd
69}
70
71// Cursor returns the cursor of the update title input
72func (s *SessionItem) Cursor() *tea.Cursor {
73 return s.updateTitleInput.Cursor()
74}
75
76// Render returns the string representation of the session item.
77func (s *SessionItem) Render(width int) string {
78 info := humanize.Time(time.Unix(s.UpdatedAt, 0))
79 styles := ListItemStyles{
80 ItemBlurred: s.t.Dialog.NormalItem,
81 ItemFocused: s.t.Dialog.SelectedItem,
82 InfoTextBlurred: s.t.Subtle,
83 InfoTextFocused: s.t.Base,
84 }
85
86 switch s.sessionsMode {
87 case sessionsModeDeleting:
88 styles.ItemBlurred = s.t.Dialog.Sessions.DeletingItemBlurred
89 styles.ItemFocused = s.t.Dialog.Sessions.DeletingItemFocused
90 case sessionsModeUpdating:
91 styles.ItemBlurred = s.t.Dialog.Sessions.RenamingItemBlurred
92 styles.ItemFocused = s.t.Dialog.Sessions.RenamingingItemFocused
93 if s.focused {
94 inputWidth := width - styles.InfoTextFocused.GetHorizontalFrameSize()
95 s.updateTitleInput.SetWidth(inputWidth)
96 s.updateTitleInput.Placeholder = ansi.Truncate(s.Title, width, "…")
97 return styles.ItemFocused.Render(s.updateTitleInput.View())
98 }
99 }
100
101 return renderItem(styles, s.Title, info, s.focused, width, s.cache, &s.m)
102}
103
104type ListItemStyles struct {
105 ItemBlurred lipgloss.Style
106 ItemFocused lipgloss.Style
107 InfoTextBlurred lipgloss.Style
108 InfoTextFocused lipgloss.Style
109}
110
111func renderItem(t ListItemStyles, title string, info string, focused bool, width int, cache map[int]string, m *fuzzy.Match) string {
112 if cache == nil {
113 cache = make(map[int]string)
114 }
115
116 cached, ok := cache[width]
117 if ok {
118 return cached
119 }
120
121 style := t.ItemBlurred
122 if focused {
123 style = t.ItemFocused
124 }
125
126 var infoText string
127 var infoWidth int
128 lineWidth := width
129 if len(info) > 0 {
130 infoText = fmt.Sprintf(" %s ", info)
131 if focused {
132 infoText = t.InfoTextFocused.Render(infoText)
133 } else {
134 infoText = t.InfoTextBlurred.Render(infoText)
135 }
136
137 infoWidth = lipgloss.Width(infoText)
138 }
139
140 title = ansi.Truncate(title, max(0, lineWidth-infoWidth), "…")
141 titleWidth := lipgloss.Width(title)
142 gap := strings.Repeat(" ", max(0, lineWidth-titleWidth-infoWidth))
143 content := title
144 if m != nil && len(m.MatchedIndexes) > 0 {
145 var lastPos int
146 parts := make([]string, 0)
147 ranges := matchedRanges(m.MatchedIndexes)
148 for _, rng := range ranges {
149 start, stop := bytePosToVisibleCharPos(title, rng)
150 if start > lastPos {
151 parts = append(parts, ansi.Cut(title, lastPos, start))
152 }
153 // NOTE: We're using [ansi.Style] here instead of [lipglosStyle]
154 // because we can control the underline start and stop more
155 // precisely via [ansi.AttrUnderline] and [ansi.AttrNoUnderline]
156 // which only affect the underline attribute without interfering
157 // with other style attributes.
158 parts = append(parts,
159 ansi.NewStyle().Underline(true).String(),
160 ansi.Cut(title, start, stop+1),
161 ansi.NewStyle().Underline(false).String(),
162 )
163 lastPos = stop + 1
164 }
165 if lastPos < ansi.StringWidth(title) {
166 parts = append(parts, ansi.Cut(title, lastPos, ansi.StringWidth(title)))
167 }
168
169 content = strings.Join(parts, "")
170 }
171
172 content = style.Render(content + gap + infoText)
173 cache[width] = content
174 return content
175}
176
177// SetFocused sets the focus state of the session item.
178func (s *SessionItem) SetFocused(focused bool) {
179 if s.focused != focused {
180 s.cache = nil
181 }
182 s.focused = focused
183}
184
185// sessionItems takes a slice of [session.Session]s and convert them to a slice
186// of [ListItem]s.
187func sessionItems(t *styles.Styles, mode sessionsMode, sessions ...session.Session) []list.FilterableItem {
188 items := make([]list.FilterableItem, len(sessions))
189 for i, s := range sessions {
190 item := &SessionItem{Session: s, t: t, sessionsMode: mode}
191 if mode == sessionsModeUpdating {
192 item.updateTitleInput = textinput.New()
193 item.updateTitleInput.SetVirtualCursor(false)
194 item.updateTitleInput.Prompt = ""
195 inputStyle := t.TextInput
196 inputStyle.Focused.Placeholder = t.Dialog.Sessions.RenamingPlaceholder
197 item.updateTitleInput.SetStyles(inputStyle)
198 item.updateTitleInput.Focus()
199 }
200 items[i] = item
201 }
202 return items
203}
204
205func matchedRanges(in []int) [][2]int {
206 if len(in) == 0 {
207 return [][2]int{}
208 }
209 current := [2]int{in[0], in[0]}
210 if len(in) == 1 {
211 return [][2]int{current}
212 }
213 var out [][2]int
214 for i := 1; i < len(in); i++ {
215 if in[i] == current[1]+1 {
216 current[1] = in[i]
217 } else {
218 out = append(out, current)
219 current = [2]int{in[i], in[i]}
220 }
221 }
222 out = append(out, current)
223 return out
224}
225
226func bytePosToVisibleCharPos(str string, rng [2]int) (int, int) {
227 bytePos, byteStart, byteStop := 0, rng[0], rng[1]
228 pos, start, stop := 0, 0, 0
229 gr := uniseg.NewGraphemes(str)
230 for byteStart > bytePos {
231 if !gr.Next() {
232 break
233 }
234 bytePos += len(gr.Str())
235 pos += max(1, gr.Width())
236 }
237 start = pos
238 for byteStop > bytePos {
239 if !gr.Next() {
240 break
241 }
242 bytePos += len(gr.Str())
243 pos += max(1, gr.Width())
244 }
245 stop = pos
246 return start, stop
247}