xonecas.io
62159
Sy

symb / files

symb / internal / tui / modal / modal.go

7.6 KB
1package modal
2
3import (
4	"strings"
5	"time"
6
7	tea "charm.land/bubbletea/v2"
8	"charm.land/lipgloss/v2"
9)
10
11// Action is the result of handling a message. nil means no action.
12type Action any
13
14// ActionClose signals the modal should be dismissed.
15type ActionClose struct{}
16
17// ActionSelect signals an item was chosen.
18type ActionSelect struct{ Item Item }
19
20// Item is a single entry in the list.
21type Item struct {
22	Name string
23	Desc string
24}
25
26// SearchFunc is called with the current query to produce results.
27type SearchFunc func(query string) []Item
28
29// Colors holds the theme colors for the modal.
30type Colors struct {
31	Fg     string
32	Bg     string
33	Dim    string
34	SelFg  string
35	SelBg  string
36	Border string
37}
38
39const (
40	debounceDelay = 250 * time.Millisecond
41
42	keyDown      = "down"
43	keyBackspace = "backspace"
44)
45
46// debounceMsg is sent after the debounce timer fires.
47type debounceMsg struct{ seq int }
48
49type searchResultsMsg struct {
50	seq   int
51	items []Item
52}
53
54// Model is a generic input+list modal.
55type Model struct {
56	input    []rune
57	cursor   int
58	items    []Item
59	selected int
60	inList   bool // true = list focused, false = input focused
61
62	searchFn SearchFunc
63	seq      int // debounce sequence counter
64
65	colors Colors
66
67	// Prompt shown before the input text.
68	Prompt string
69
70	// WidthPct controls the modal width as a percent of app width.
71	WidthPct int
72}
73
74// New creates a modal with the given search function.
75func New(searchFn SearchFunc, prompt string, colors Colors) Model {
76	m := Model{
77		searchFn: searchFn,
78		Prompt:   prompt,
79		colors:   colors,
80	}
81	// Initial search with empty query.
82	m.items = searchFn("")
83	return m
84}
85
86// DebounceCmd returns a tea.Cmd that fires after the debounce delay.
87func (m *Model) DebounceCmd() tea.Cmd {
88	seq := m.seq
89	return tea.Tick(debounceDelay, func(time.Time) tea.Msg {
90		return debounceMsg{seq: seq}
91	})
92}
93
94// HandleMsg processes a tea.Msg and returns an optional Action.
95// The second return is a tea.Cmd the parent must dispatch (for debounce).
96func (m *Model) HandleMsg(msg tea.Msg) (Action, tea.Cmd) {
97	switch msg := msg.(type) {
98	case tea.KeyPressMsg:
99		return m.handleKey(msg)
100	case debounceMsg:
101		if msg.seq == m.seq {
102			return nil, m.searchCmd(string(m.input), msg.seq)
103		}
104		return nil, nil
105	case searchResultsMsg:
106		if msg.seq == m.seq {
107			m.items = msg.items
108			m.selected = 0
109			m.inList = false
110		}
111		return nil, nil
112	}
113	return nil, nil
114}
115
116func (m *Model) handleKey(msg tea.KeyPressMsg) (Action, tea.Cmd) {
117	switch msg.Keystroke() {
118	case "esc":
119		return ActionClose{}, nil
120	case "enter":
121		return m.handleEnter()
122	case "up", keyDown:
123		m.handleNav(msg.Keystroke())
124		return nil, nil
125	case keyBackspace, "delete", "ctrl+u", "ctrl+k":
126		return nil, m.handleDelete(msg.Keystroke())
127	case "left", "right", "home", "end", "ctrl+a", "ctrl+e":
128		m.handleCursor(msg.Keystroke())
129		return nil, nil
130	}
131
132	// Rune input.
133	if !m.inList && msg.Text != "" {
134		for _, r := range msg.Text {
135			m.input = append(m.input[:m.cursor], append([]rune{r}, m.input[m.cursor:]...)...)
136			m.cursor++
137		}
138		m.seq++
139		return nil, m.DebounceCmd()
140	}
141
142	return nil, nil
143}
144
145func (m *Model) searchCmd(query string, seq int) tea.Cmd {
146	if m.searchFn == nil {
147		return nil
148	}
149	return func() tea.Msg {
150		items := m.searchFn(query)
151		return searchResultsMsg{seq: seq, items: items}
152	}
153}
154
155func (m *Model) handleEnter() (Action, tea.Cmd) {
156	if len(m.items) == 0 {
157		return nil, nil
158	}
159	idx := m.selected
160	if idx >= len(m.items) {
161		idx = 0
162	}
163	return ActionSelect{Item: m.items[idx]}, nil
164}
165
166func (m *Model) handleNav(key string) {
167	switch key {
168	case "up":
169		if m.inList {
170			if m.selected > 0 {
171				m.selected--
172			} else {
173				m.inList = false
174			}
175		}
176	case keyDown:
177		if !m.inList {
178			if len(m.items) > 0 {
179				m.inList = true
180				m.selected = 0
181			}
182		} else if m.selected < len(m.items)-1 {
183			m.selected++
184		}
185	}
186}
187
188func (m *Model) handleDelete(key string) tea.Cmd {
189	switch key {
190	case keyBackspace:
191		if m.cursor > 0 {
192			m.input = append(m.input[:m.cursor-1], m.input[m.cursor:]...)
193			m.cursor--
194			m.seq++
195			return m.DebounceCmd()
196		}
197	case "delete":
198		if m.cursor < len(m.input) {
199			m.input = append(m.input[:m.cursor], m.input[m.cursor+1:]...)
200			m.seq++
201			return m.DebounceCmd()
202		}
203	case "ctrl+u":
204		m.input = m.input[m.cursor:]
205		m.cursor = 0
206		m.seq++
207		return m.DebounceCmd()
208	case "ctrl+k":
209		m.input = m.input[:m.cursor]
210		m.seq++
211		return m.DebounceCmd()
212	}
213	return nil
214}
215
216func (m *Model) handleCursor(key string) {
217	if m.inList {
218		return
219	}
220	switch key {
221	case "left":
222		if m.cursor > 0 {
223			m.cursor--
224		}
225	case "right":
226		if m.cursor < len(m.input) {
227			m.cursor++
228		}
229	case "home", "ctrl+a":
230		m.cursor = 0
231	case "end", "ctrl+e":
232		m.cursor = len(m.input)
233	}
234}
235
236// View renders the modal at the given app width and height.
237func (m *Model) View(appWidth, appHeight int) string {
238	widthPct := m.WidthPct
239	if widthPct <= 0 {
240		widthPct = 80
241	}
242	w := appWidth * widthPct / 100
243	h := appHeight * 80 / 100
244	if w < 30 {
245		w = 30
246	}
247	if h < 8 {
248		h = 8
249	}
250
251	innerW := w - 6 // border + padding
252	if innerW < 10 {
253		innerW = 10
254	}
255
256	prompt := m.Prompt
257	if prompt == "" {
258		prompt = "> "
259	}
260
261	inputLine := m.renderInput(prompt)
262	listHeight := h - 4 // border top/bottom + input + divider
263	if listHeight < 1 {
264		listHeight = 1
265	}
266
267	dimStyle := lipgloss.NewStyle().Foreground(lipgloss.Color(m.colors.Dim))
268	divider := dimStyle.Render(strings.Repeat("\u2500", innerW))
269	listLines := m.renderList(innerW, listHeight)
270
271	content := inputLine + "\n" + divider
272	for _, l := range listLines {
273		content += "\n" + l
274	}
275
276	bg := lipgloss.Color(m.colors.Bg)
277	box := lipgloss.NewStyle().
278		Border(lipgloss.RoundedBorder()).
279		BorderForeground(lipgloss.Color(m.colors.Border)).
280		BorderBackground(bg).
281		Foreground(lipgloss.Color(m.colors.Fg)).
282		Background(bg).
283		Padding(0, 1).
284		Width(w - 2).
285		Render(content)
286
287	return lipgloss.Place(appWidth, appHeight, lipgloss.Center, lipgloss.Center, box,
288		lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(bg)))
289}
290
291func (m *Model) renderInput(prompt string) string {
292	if m.inList {
293		return prompt + string(m.input)
294	}
295	before := string(m.input[:m.cursor])
296	cursorStyle := lipgloss.NewStyle().Reverse(true)
297	cursorChar := " "
298	after := ""
299	if m.cursor < len(m.input) {
300		cursorChar = string(m.input[m.cursor])
301		after = string(m.input[m.cursor+1:])
302	}
303	return prompt + before + cursorStyle.Render(cursorChar) + after
304}
305
306func (m *Model) renderList(innerW, listHeight int) []string {
307	scrollOff := 0
308	if m.selected >= listHeight {
309		scrollOff = m.selected - listHeight + 1
310	}
311
312	bg := lipgloss.Color(m.colors.Bg)
313	baseStyle := lipgloss.NewStyle().Foreground(lipgloss.Color(m.colors.Fg)).Background(bg)
314	dimStyle := lipgloss.NewStyle().
315		Foreground(lipgloss.Color(m.colors.Dim)).
316		Background(bg)
317	selStyle := lipgloss.NewStyle().
318		Foreground(lipgloss.Color(m.colors.SelFg)).
319		Background(lipgloss.Color(m.colors.SelBg))
320
321	var lines []string
322	for i := scrollOff; i < len(m.items) && len(lines) < listHeight; i++ {
323		item := m.items[i]
324		if i == m.selected && m.inList {
325			lines = append(lines, selStyle.Render(padRight(item.Name, innerW)))
326		} else {
327			name := baseStyle.Render(item.Name)
328			visW := lipgloss.Width(item.Name)
329			desc := ""
330			if item.Desc != "" {
331				desc = dimStyle.Render("  " + item.Desc)
332				visW += 2 + lipgloss.Width(item.Desc)
333			}
334			pad := ""
335			if visW < innerW {
336				pad = baseStyle.Render(strings.Repeat(" ", innerW-visW))
337			}
338			lines = append(lines, name+desc+pad)
339		}
340	}
341
342	for len(lines) < listHeight {
343		lines = append(lines, baseStyle.Render(strings.Repeat(" ", innerW)))
344	}
345	return lines
346}
347
348func padRight(s string, w int) string {
349	vis := lipgloss.Width(s)
350	if vis >= w {
351		return s
352	}
353	return s + strings.Repeat(" ", w-vis)
354}