Repository navigation
Expand file tree
/
Copy pathmulti_select_with_search.go
More file actions
457 lines (396 loc) · 11.3 KB
/
Copy pathmulti_select_with_search.go
File metadata and controls
457 lines (396 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package prompter
import (
"fmt"
"io"
"strings"
"sync/atomic"
"charm.land/bubbles/v2/key"
"charm.land/bubbles/v2/spinner"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"charm.land/huh/v2"
"charm.land/lipgloss/v2"
)
// multiSelectSearchField is a custom huh Field that combines a text input
// for searching with a multi-select list. Unlike huh's built-in OptionsFunc,
// search results are loaded synchronously when the user presses Enter in
// the search input, avoiding goroutine races with selection state.
type multiSelectSearchField struct {
// configuration
title string
searchTitle string
searchFunc func(string) MultiSelectSearchResult
// state
mode msMode // which sub-component has focus
search textinput.Model
cursor int
loading bool
spinner spinner.Model
// options and selections
options []msOption
selected map[string]bool // key → selected (source of truth)
optionLabels map[string]string // key → display label
lastQuery string
defaultValues []string
persistent []string
// field metadata
key string
err error
focused bool
width int
height int
theme huh.Theme
hasDarkBg bool
position huh.FieldPosition
// onSearchDone stores a func() that is called each time an async search
// completes. It is unset in production and used only in tests to
// synchronize on search completion without relying on fixed-duration
// sleeps. atomic.Value is used because the hook is written by the test
// goroutine and invoked by bubbletea's event-loop goroutine.
onSearchDone atomic.Value
}
type msMode int
const (
msModeSearch msMode = iota
msModeSelect
)
type msOption struct {
label string
value string
}
// msSearchResultMsg carries search results back from the background goroutine.
type msSearchResultMsg struct {
query string
result MultiSelectSearchResult
}
func newMultiSelectSearchField(
title, searchTitle string,
defaults, persistent []string,
searchFunc func(string) MultiSelectSearchResult,
) *multiSelectSearchField {
ti := textinput.New()
ti.Prompt = "> "
ti.Placeholder = "Type to search"
ti.Focus()
selected := make(map[string]bool)
for _, k := range defaults {
selected[k] = true
}
m := &multiSelectSearchField{
title: title,
searchTitle: searchTitle,
searchFunc: searchFunc,
mode: msModeSearch,
search: ti,
selected: selected,
optionLabels: make(map[string]string),
defaultValues: defaults,
persistent: persistent,
height: 10,
spinner: spinner.New(spinner.WithSpinner(spinner.Line)),
}
// Load initial results synchronously (form hasn't started yet).
m.applySearchResult("", m.searchFunc(""))
return m
}
// startSearch launches an async search and returns a tea.Cmd that will
// deliver the result via msSearchResultMsg.
func (m *multiSelectSearchField) startSearch(query string) tea.Cmd {
m.loading = true
searchFunc := m.searchFunc
return tea.Batch(
func() tea.Msg {
return msSearchResultMsg{query: query, result: searchFunc(query)}
},
m.spinner.Tick,
)
}
// applySearchResult processes a completed search and rebuilds the option list.
func (m *multiSelectSearchField) applySearchResult(query string, result MultiSelectSearchResult) {
m.loading = false
m.lastQuery = query
if result.Err != nil {
m.err = result.Err
return
}
if len(result.Keys) != len(result.Labels) {
m.err = fmt.Errorf("search returned mismatched keys and labels: %d keys, %d labels", len(result.Keys), len(result.Labels))
return
}
for i, k := range result.Keys {
m.optionLabels[k] = result.Labels[i]
}
// Build option list: selected items first, then results, then persistent.
var options []msOption
seen := make(map[string]bool)
// 1. Currently selected items.
for _, k := range m.selectedKeys() {
if seen[k] {
continue
}
seen[k] = true
options = append(options, msOption{label: m.label(k), value: k})
}
// 2. Search results.
for i, k := range result.Keys {
if seen[k] {
continue
}
seen[k] = true
l := result.Labels[i]
if l == "" {
l = k
}
options = append(options, msOption{label: l, value: k})
}
// 3. Persistent options.
for _, k := range m.persistent {
if seen[k] {
continue
}
seen[k] = true
options = append(options, msOption{label: m.label(k), value: k})
}
m.options = options
m.cursor = 0
m.err = nil
if hook, ok := m.onSearchDone.Load().(func()); ok {
hook()
}
}
func (m *multiSelectSearchField) selectedKeys() []string {
keys := make([]string, 0)
// Maintain order: defaults first, then any added during this session.
seen := make(map[string]bool)
for _, k := range m.defaultValues {
if m.selected[k] && !seen[k] {
keys = append(keys, k)
seen[k] = true
}
}
for _, o := range m.options {
if m.selected[o.value] && !seen[o.value] {
keys = append(keys, o.value)
seen[o.value] = true
}
}
return keys
}
func (m *multiSelectSearchField) label(key string) string {
if l, ok := m.optionLabels[key]; ok && l != "" {
return l
}
return key
}
// --- huh.Field interface ---
func (m *multiSelectSearchField) Init() tea.Cmd {
return nil
}
func (m *multiSelectSearchField) Update(msg tea.Msg) (huh.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.BackgroundColorMsg:
m.hasDarkBg = msg.IsDark()
case msSearchResultMsg:
m.applySearchResult(msg.query, msg.result)
m.mode = msModeSelect
m.search.Blur()
return m, nil
case spinner.TickMsg:
if !m.loading {
break
}
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
case tea.KeyPressMsg:
if m.loading {
return m, nil // ignore keys while loading
}
switch m.mode {
case msModeSearch:
return m.updateSearch(msg)
case msModeSelect:
return m.updateSelect(msg)
}
}
return m, nil
}
func (m *multiSelectSearchField) updateSearch(msg tea.KeyPressMsg) (huh.Model, tea.Cmd) {
switch {
case key.Matches(msg, key.NewBinding(key.WithKeys("enter", "tab"))):
query := m.search.Value()
if query == m.lastQuery {
// Query unchanged — just switch to select mode.
m.mode = msModeSelect
m.search.Blur()
return m, nil
}
// New query — clear input and search in background with spinner.
m.search.SetValue("")
return m, m.startSearch(query)
case key.Matches(msg, key.NewBinding(key.WithKeys("shift+tab"))):
return m, huh.PrevField
default:
var cmd tea.Cmd
m.search, cmd = m.search.Update(msg)
return m, cmd
}
}
func (m *multiSelectSearchField) updateSelect(msg tea.KeyPressMsg) (huh.Model, tea.Cmd) {
switch {
case key.Matches(msg, key.NewBinding(key.WithKeys("shift+tab"))):
// Back to search mode.
m.mode = msModeSearch
m.search.Focus()
return m, nil
case key.Matches(msg, key.NewBinding(key.WithKeys("enter"))):
return m, huh.NextField
case key.Matches(msg, key.NewBinding(key.WithKeys("up", "k"))):
if m.cursor > 0 {
m.cursor--
}
return m, nil
case key.Matches(msg, key.NewBinding(key.WithKeys("down", "j"))):
if m.cursor < len(m.options)-1 {
m.cursor++
}
return m, nil
case key.Matches(msg, key.NewBinding(key.WithKeys("space", "x"))):
if len(m.options) > 0 {
k := m.options[m.cursor].value
m.selected[k] = !m.selected[k]
if !m.selected[k] {
delete(m.selected, k)
}
}
return m, nil
}
return m, nil
}
func (m *multiSelectSearchField) View() string {
styles := m.activeStyles()
var sb strings.Builder
// Title.
if m.title != "" {
sb.WriteString(styles.Title.Render(m.title))
sb.WriteString("\n")
}
// Search input.
if m.searchTitle != "" {
sb.WriteString(styles.Description.Render(m.searchTitle))
sb.WriteString("\n")
}
sb.WriteString(m.search.View())
sb.WriteString("\n")
// Options list.
if m.loading {
m.spinner.Style = styles.MultiSelectSelector.UnsetString()
sb.WriteString(m.spinner.View() + " Loading...")
sb.WriteString("\n")
} else if len(m.options) == 0 {
sb.WriteString(styles.UnselectedOption.Render(" No results"))
sb.WriteString("\n")
} else {
for i, o := range m.options {
cursor := m.mode == msModeSelect && i == m.cursor
isSelected := m.selected[o.value]
sb.WriteString(m.renderOption(o, cursor, isSelected))
sb.WriteString("\n")
}
}
return styles.Base.Width(m.width).Height(m.height).Render(sb.String())
}
func (m *multiSelectSearchField) renderOption(o msOption, cursor, selected bool) string {
styles := m.activeStyles()
var parts []string
if cursor {
parts = append(parts, styles.MultiSelectSelector.String())
} else {
parts = append(parts, strings.Repeat(" ", lipgloss.Width(styles.MultiSelectSelector.String())))
}
if selected {
parts = append(parts, styles.SelectedPrefix.String())
parts = append(parts, styles.SelectedOption.Render(o.label))
} else {
parts = append(parts, styles.UnselectedPrefix.String())
parts = append(parts, styles.UnselectedOption.Render(o.label))
}
return lipgloss.JoinHorizontal(lipgloss.Left, parts...)
}
func (m *multiSelectSearchField) activeStyles() *huh.FieldStyles {
theme := m.theme
if theme == nil {
theme = huh.ThemeFunc(huh.ThemeCharm)
}
if m.focused {
return &theme.Theme(m.hasDarkBg).Focused
}
return &theme.Theme(m.hasDarkBg).Blurred
}
func (m *multiSelectSearchField) Focus() tea.Cmd {
m.focused = true
if m.mode == msModeSearch {
return m.search.Focus()
}
return nil
}
func (m *multiSelectSearchField) Blur() tea.Cmd {
m.focused = false
m.search.Blur()
return nil
}
func (m *multiSelectSearchField) Error() error { return m.err }
func (*multiSelectSearchField) Skip() bool { return false }
func (*multiSelectSearchField) Zoom() bool { return false }
func (m *multiSelectSearchField) GetKey() string { return m.key }
func (m *multiSelectSearchField) GetValue() any { return m.selectedKeys() }
func (m *multiSelectSearchField) Run() error { return huh.Run(m) }
func (m *multiSelectSearchField) RunAccessible(w io.Writer, r io.Reader) error {
_, _ = fmt.Fprintln(w, "MultiSelectWithSearch accessible mode not implemented")
return nil
}
func (m *multiSelectSearchField) KeyBinds() []key.Binding {
if m.mode == msModeSearch {
return []key.Binding{
key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "search")),
key.NewBinding(key.WithKeys("shift+tab"), key.WithHelp("shift+tab", "back")),
}
}
return []key.Binding{
key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "toggle")),
key.NewBinding(key.WithKeys("up"), key.WithHelp("↑", "up")),
key.NewBinding(key.WithKeys("down"), key.WithHelp("↓", "down")),
key.NewBinding(key.WithKeys("shift+tab"), key.WithHelp("shift+tab", "search")),
key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "confirm")),
}
}
func (m *multiSelectSearchField) WithTheme(theme huh.Theme) huh.Field {
if m.theme != nil {
return m
}
m.theme = theme
styles := theme.Theme(m.hasDarkBg)
st := m.search.Styles()
st.Cursor.Color = styles.Focused.TextInput.Cursor.GetForeground()
st.Focused.Prompt = styles.Focused.TextInput.Prompt
st.Focused.Text = styles.Focused.TextInput.Text
st.Focused.Placeholder = styles.Focused.TextInput.Placeholder
m.search.SetStyles(st)
return m
}
func (m *multiSelectSearchField) WithKeyMap(k *huh.KeyMap) huh.Field {
return m
}
func (m *multiSelectSearchField) WithWidth(width int) huh.Field {
m.width = width
m.search.SetWidth(width)
return m
}
func (m *multiSelectSearchField) WithHeight(height int) huh.Field {
m.height = height
return m
}
func (m *multiSelectSearchField) WithPosition(p huh.FieldPosition) huh.Field {
m.position = p
return m
}