Debian Codegraph @

field_multiselect.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "fmt"
6 "io"
7 "os"
8 "slices"
9 "strings"
10 "time"
11
12 "github.com/charmbracelet/bubbles/key"
13 "github.com/charmbracelet/bubbles/spinner"
14 "github.com/charmbracelet/bubbles/textinput"
15 "github.com/charmbracelet/bubbles/viewport"
16 tea "github.com/charmbracelet/bubbletea"
17 "github.com/charmbracelet/huh/internal/accessibility"
18 "github.com/charmbracelet/lipgloss"
19 )
20
21 // MultiSelect is a form multi-select field.
22 type MultiSelect[T comparable] struct {
23 accessor Accessor[[]T]
24 key string
25 id int
26
27 // customization
28 title Eval[string]
29 description Eval[string]
30 options Eval[[]Option[T]]
31 filterable bool
32 filteredOptions []Option[T]
33 limit int
34 height int
35
36 // error handling
37 validate func([]T) error
38 err error
39
40 // state
41 cursor int
42 focused bool
43 filtering bool
44 filter textinput.Model
45 viewport viewport.Model
46 spinner spinner.Model
47
48 // options
49 width int
50 accessible bool // Deprecated: use RunAccessible instead.
51 theme *Theme
52 keymap MultiSelectKeyMap
53 }
54
55 // NewMultiSelect returns a new multi-select field.
56 func NewMultiSelect[T comparable]() *MultiSelect[T] {
57 filter := textinput.New()
58 filter.Prompt = "/"
59
60 s := spinner.New(spinner.WithSpinner(spinner.Line))
61
62 return &MultiSelect[T]{
63 accessor: &EmbeddedAccessor[[]T]{},
64 validate: func([]T) error { return nil },
65 filtering: false,
66 filter: filter,
67 id: nextID(),
68 options: Eval[[]Option[T]]{cache: make(map[uint64][]Option[T])},
69 title: Eval[string]{cache: make(map[uint64]string)},
70 description: Eval[string]{cache: make(map[uint64]string)},
71 spinner: s,
72 filterable: true,
73 }
74 }
75
76 // Value sets the value of the multi-select field.
77 func (m *MultiSelect[T]) Value(value *[]T) *MultiSelect[T] {
78 return m.Accessor(NewPointerAccessor(value))
79 }
80
81 // Accessor sets the accessor of the input field.
82 func (m *MultiSelect[T]) Accessor(accessor Accessor[[]T]) *MultiSelect[T] {
83 m.accessor = accessor
84 for i, o := range m.options.val {
85 if slices.Contains(m.accessor.Get(), o.Value) {
86 m.options.val[i].selected = true
87 }
88 }
89 return m
90 }
91
92 // Key sets the key of the select field which can be used to retrieve the value
93 // after submission.
94 func (m *MultiSelect[T]) Key(key string) *MultiSelect[T] {
95 m.key = key
96 return m
97 }
98
99 // Title sets the title of the multi-select field.
100 func (m *MultiSelect[T]) Title(title string) *MultiSelect[T] {
101 m.title.val = title
102 m.title.fn = nil
103 return m
104 }
105
106 // TitleFunc sets the title func of the multi-select field.
107 func (m *MultiSelect[T]) TitleFunc(f func() string, bindings any) *MultiSelect[T] {
108 m.title.fn = f
109 m.title.bindings = bindings
110 return m
111 }
112
113 // Description sets the description of the multi-select field.
114 func (m *MultiSelect[T]) Description(description string) *MultiSelect[T] {
115 m.description.val = description
116 return m
117 }
118
119 // DescriptionFunc sets the description func of the multi-select field.
120 func (m *MultiSelect[T]) DescriptionFunc(f func() string, bindings any) *MultiSelect[T] {
121 m.description.fn = f
122 m.description.bindings = bindings
123 return m
124 }
125
126 // Options sets the options of the multi-select field.
127 func (m *MultiSelect[T]) Options(options ...Option[T]) *MultiSelect[T] {
128 if len(options) <= 0 {
129 return m
130 }
131
132 m.options.val = options
133 m.filteredOptions = options
134 m.selectOptions()
135 m.updateViewportHeight()
136 return m
137 }
138
139 func (m *MultiSelect[T]) selectOptions() {
140 // Set the cursor to the existing value or the last selected option.
141 for i, o := range m.options.val {
142 for _, v := range m.accessor.Get() {
143 if o.Value == v {
144 m.options.val[i].selected = true
145 }
146 }
147 }
148
149 for i, o := range m.options.val {
150 if !o.selected {
151 continue
152 }
153 m.cursor = i
154 m.viewport.YOffset = i
155 break
156 }
157 }
158
159 // OptionsFunc sets the options func of the multi-select field.
160 func (m *MultiSelect[T]) OptionsFunc(f func() []Option[T], bindings any) *MultiSelect[T] {
161 m.options.fn = f
162 m.options.bindings = bindings
163 m.filteredOptions = make([]Option[T], 0)
164 // If there is no height set, we should attach a static height since these
165 // options are possibly dynamic.
166 if m.height <= 0 {
167 m.height = defaultHeight
168 m.updateViewportHeight()
169 }
170 return m
171 }
172
173 // Filterable sets the multi-select field as filterable.
174 func (m *MultiSelect[T]) Filterable(filterable bool) *MultiSelect[T] {
175 m.filterable = filterable
176 return m
177 }
178
179 // Filtering sets the filtering state of the multi-select field.
180 func (m *MultiSelect[T]) Filtering(filtering bool) *MultiSelect[T] {
181 m.filtering = filtering
182 m.filter.Focus()
183 return m
184 }
185
186 // Limit sets the limit of the multi-select field.
187 func (m *MultiSelect[T]) Limit(limit int) *MultiSelect[T] {
188 m.limit = limit
189 m.setSelectAllHelp()
190 return m
191 }
192
193 // Height sets the height of the multi-select field.
194 func (m *MultiSelect[T]) Height(height int) *MultiSelect[T] {
195 // What we really want to do is set the height of the viewport, but we
196 // need a theme applied before we can calcualate its height.
197 m.height = height
198 m.updateViewportHeight()
199 return m
200 }
201
202 // Validate sets the validation function of the multi-select field.
203 func (m *MultiSelect[T]) Validate(validate func([]T) error) *MultiSelect[T] {
204 m.validate = validate
205 return m
206 }
207
208 // Error returns the error of the multi-select field.
209 func (m *MultiSelect[T]) Error() error {
210 return m.err
211 }
212
213 // Skip returns whether the multiselect should be skipped or should be blocking.
214 func (*MultiSelect[T]) Skip() bool {
215 return false
216 }
217
218 // Zoom returns whether the multiselect should be zoomed.
219 func (*MultiSelect[T]) Zoom() bool {
220 return false
221 }
222
223 // Focus focuses the multi-select field.
224 func (m *MultiSelect[T]) Focus() tea.Cmd {
225 m.updateValue()
226 m.focused = true
227 return nil
228 }
229
230 // Blur blurs the multi-select field.
231 func (m *MultiSelect[T]) Blur() tea.Cmd {
232 m.updateValue()
233 m.focused = false
234 return nil
235 }
236
237 // Hovered returns the value of the option under the cursor, and a bool
238 // indicating whether one was found. If there are no visible options, returns
239 // a zero-valued T and false.
240 func (m *MultiSelect[T]) Hovered() (T, bool) {
241 if len(m.filteredOptions) == 0 || m.cursor >= len(m.filteredOptions) {
242 var zero T
243 return zero, false
244 }
245 return m.filteredOptions[m.cursor].Value, true
246 }
247
248 // KeyBinds returns the help message for the multi-select field.
249 func (m *MultiSelect[T]) KeyBinds() []key.Binding {
250 m.setSelectAllHelp()
251 binds := []key.Binding{
252 m.keymap.Toggle,
253 m.keymap.Up,
254 m.keymap.Down,
255 }
256 if m.filterable {
257 binds = append(
258 binds,
259 m.keymap.Filter,
260 m.keymap.SetFilter,
261 m.keymap.ClearFilter,
262 )
263 }
264 binds = append(
265 binds,
266 m.keymap.Prev,
267 m.keymap.Submit,
268 m.keymap.Next,
269 m.keymap.SelectAll,
270 m.keymap.SelectNone,
271 )
272 return binds
273 }
274
275 // Init initializes the multi-select field.
276 func (m *MultiSelect[T]) Init() tea.Cmd {
277 return nil
278 }
279
280 // Update updates the multi-select field.
281 func (m *MultiSelect[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
282 var cmds []tea.Cmd
283
284 // Enforce height on the viewport during update as we need themes to
285 // be applied before we can calculate the height.
286 m.updateViewportHeight()
287
288 var cmd tea.Cmd
289 if m.filtering {
290 m.filter, cmd = m.filter.Update(msg)
291 m.setSelectAllHelp()
292 cmds = append(cmds, cmd)
293 }
294
295 switch msg := msg.(type) {
296 case updateFieldMsg:
297 var fieldCmds []tea.Cmd
298 if ok, hash := m.title.shouldUpdate(); ok {
299 m.title.bindingsHash = hash
300 if !m.title.loadFromCache() {
301 m.title.loading = true
302 fieldCmds = append(fieldCmds, func() tea.Msg {
303 return updateTitleMsg{id: m.id, title: m.title.fn(), hash: hash}
304 })
305 }
306 }
307 if ok, hash := m.description.shouldUpdate(); ok {
308 m.description.bindingsHash = hash
309 if !m.description.loadFromCache() {
310 m.description.loading = true
311 fieldCmds = append(fieldCmds, func() tea.Msg {
312 return updateDescriptionMsg{id: m.id, description: m.description.fn(), hash: hash}
313 })
314 }
315 }
316 if ok, hash := m.options.shouldUpdate(); ok {
317 m.options.bindingsHash = hash
318 if m.options.loadFromCache() {
319 m.filteredOptions = m.options.val
320 m.updateValue()
321 m.cursor = clamp(m.cursor, 0, len(m.filteredOptions)-1)
322 } else {
323 m.options.loading = true
324 m.options.loadingStart = time.Now()
325 fieldCmds = append(fieldCmds, func() tea.Msg {
326 return updateOptionsMsg[T]{id: m.id, options: m.options.fn(), hash: hash}
327 }, m.spinner.Tick)
328 }
329 }
330
331 return m, tea.Batch(fieldCmds...)
332
333 case spinner.TickMsg:
334 if !m.options.loading {
335 break
336 }
337 m.spinner, cmd = m.spinner.Update(msg)
338 return m, cmd
339
340 case updateTitleMsg:
341 if msg.id == m.id && msg.hash == m.title.bindingsHash {
342 m.title.update(msg.title)
343 }
344 case updateDescriptionMsg:
345 if msg.id == m.id && msg.hash == m.description.bindingsHash {
346 m.description.update(msg.description)
347 }
348 case updateOptionsMsg[T]:
349 if msg.id == m.id && msg.hash == m.options.bindingsHash {
350 m.options.update(msg.options)
351 m.selectOptions()
352 // since we're updating the options, we need to reset the cursor.
353 m.filteredOptions = m.options.val
354 m.updateValue()
355 m.cursor = clamp(m.cursor, 0, len(m.filteredOptions)-1)
356 }
357 case tea.KeyMsg:
358 m.err = nil
359 switch {
360 case key.Matches(msg, m.keymap.Filter):
361 m.setFilter(true)
362 return m, m.filter.Focus()
363 case key.Matches(msg, m.keymap.SetFilter):
364 if len(m.filteredOptions) <= 0 {
365 m.filter.SetValue("")
366 m.filteredOptions = m.options.val
367 }
368 m.setFilter(false)
369 case key.Matches(msg, m.keymap.ClearFilter):
370 m.filter.SetValue("")
371 m.filteredOptions = m.options.val
372 m.setFilter(false)
373 case key.Matches(msg, m.keymap.Up):
374 //nolint:godox
375 // FIXME: should use keys in keymap
376 if m.filtering && msg.String() == "k" {
377 break
378 }
379
380 m.cursor = max(m.cursor-1, 0)
381 if m.cursor < m.viewport.YOffset {
382 m.viewport.SetYOffset(m.cursor)
383 }
384 case key.Matches(msg, m.keymap.Down):
385 //nolint:godox
386 // FIXME: should use keys in keymap
387 if m.filtering && msg.String() == "j" {
388 break
389 }
390
391 m.cursor = min(m.cursor+1, len(m.filteredOptions)-1)
392 if m.cursor >= m.viewport.YOffset+m.viewport.Height {
393 m.viewport.ScrollDown(1)
394 }
395 case key.Matches(msg, m.keymap.GotoTop):
396 if m.filtering {
397 break
398 }
399 m.cursor = 0
400 m.viewport.GotoTop()
401 case key.Matches(msg, m.keymap.GotoBottom):
402 if m.filtering {
403 break
404 }
405 m.cursor = len(m.filteredOptions) - 1
406 m.viewport.GotoBottom()
407 case key.Matches(msg, m.keymap.HalfPageUp):
408 m.cursor = max(m.cursor-m.viewport.Height/2, 0)
409 m.viewport.HalfPageUp()
410 case key.Matches(msg, m.keymap.HalfPageDown):
411 m.cursor = min(m.cursor+m.viewport.Height/2, len(m.filteredOptions)-1)
412 m.viewport.HalfPageDown()
413 case key.Matches(msg, m.keymap.Toggle) && !m.filtering:
414 for i, option := range m.options.val {
415 if option.Key == m.filteredOptions[m.cursor].Key {
416 if !m.options.val[m.cursor].selected && m.limit > 0 && m.numSelected() >= m.limit {
417 break
418 }
419 selected := m.options.val[i].selected
420 m.options.val[i].selected = !selected
421 m.filteredOptions[m.cursor].selected = !selected
422 }
423 }
424 m.setSelectAllHelp()
425 m.updateValue()
426 case key.Matches(msg, m.keymap.SelectAll, m.keymap.SelectNone) && m.limit <= 0:
427 selected := false
428
429 for _, option := range m.filteredOptions {
430 if !option.selected {
431 selected = true
432 break
433 }
434 }
435
436 for i, option := range m.options.val {
437 for j := range m.filteredOptions {
438 if option.Key == m.filteredOptions[j].Key {
439 m.options.val[i].selected = selected
440 m.filteredOptions[j].selected = selected
441 break
442 }
443 }
444 }
445 m.setSelectAllHelp()
446 m.updateValue()
447 case key.Matches(msg, m.keymap.Prev):
448 m.updateValue()
449 m.err = m.validate(m.accessor.Get())
450 if m.err != nil {
451 return m, nil
452 }
453 return m, PrevField
454 case key.Matches(msg, m.keymap.Next, m.keymap.Submit):
455 m.updateValue()
456 m.err = m.validate(m.accessor.Get())
457 if m.err != nil {
458 return m, nil
459 }
460 return m, NextField
461 }
462
463 if m.filtering {
464 m.filteredOptions = m.options.val
465 if m.filter.Value() != "" {
466 m.filteredOptions = nil
467 for _, option := range m.options.val {
468 if m.filterFunc(option.Key) {
469 m.filteredOptions = append(m.filteredOptions, option)
470 }
471 }
472 }
473 if len(m.filteredOptions) > 0 {
474 m.cursor = min(m.cursor, len(m.filteredOptions)-1)
475 }
476 }
477 _, offset, height := m.optionsView()
478 if offset > -1 && height > 0 && (offset < m.viewport.YOffset || height+offset >= m.viewport.YOffset+m.viewport.Height) {
479 m.viewport.SetYOffset(offset)
480 }
481 }
482
483 return m, tea.Batch(cmds...)
484 }
485
486 // updateViewportHeight updates the viewport size according to the Height setting
487 // on this multi-select field.
488 func (m *MultiSelect[T]) updateViewportHeight() {
489 // If no height is set size the viewport to the height of the options.
490 if m.height <= 0 {
491 v, _, _ := m.optionsView()
492 m.viewport.Height = lipgloss.Height(v)
493 return
494 }
495
496 offset := 0
497 if ss := m.titleView(); ss != "" {
498 offset += lipgloss.Height(ss)
499 }
500 if ss := m.descriptionView(); ss != "" {
501 offset += lipgloss.Height(ss)
502 }
503
504 m.viewport.Height = max(minHeight, m.height-offset)
505 }
506
507 // numSelected returns the total number of selected options.
508 func (m *MultiSelect[T]) numSelected() int {
509 var count int
510 for _, o := range m.options.val {
511 if o.selected {
512 count++
513 }
514 }
515 return count
516 }
517
518 // numFilteredOptionsSelected returns the number of selected options with the
519 // current filter applied.
520 func (m *MultiSelect[T]) numFilteredSelected() int {
521 var count int
522 for _, o := range m.filteredOptions {
523 if o.selected {
524 count++
525 }
526 }
527 return count
528 }
529
530 func (m *MultiSelect[T]) updateValue() {
531 value := make([]T, 0)
532 for _, option := range m.options.val {
533 if option.selected {
534 value = append(value, option.Value)
535 }
536 }
537 m.accessor.Set(value)
538 m.err = m.validate(m.accessor.Get())
539 }
540
541 func (m *MultiSelect[T]) activeStyles() *FieldStyles {
542 theme := m.theme
543 if theme == nil {
544 theme = ThemeCharm()
545 }
546 if m.focused {
547 return &theme.Focused
548 }
549 return &theme.Blurred
550 }
551
552 func (m *MultiSelect[T]) titleView() string {
553 if m.title.val == "" {
554 return ""
555 }
556 var (
557 styles = m.activeStyles()
558 sb = strings.Builder{}
559 maxWidth = m.width - styles.Base.GetHorizontalFrameSize()
560 )
561 if m.filtering {
562 sb.WriteString(m.filter.View())
563 } else if m.filter.Value() != "" {
564 sb.WriteString(styles.Title.Render(wrap(m.title.val, maxWidth)))
565 sb.WriteString(styles.Description.Render("/" + m.filter.Value()))
566 } else {
567 sb.WriteString(styles.Title.Render(wrap(m.title.val, maxWidth)))
568 }
569 if m.err != nil {
570 sb.WriteString(styles.ErrorIndicator.String())
571 }
572 return sb.String()
573 }
574
575 func (m *MultiSelect[T]) descriptionView() string {
576 if m.description.val == "" {
577 return ""
578 }
579 maxWidth := m.width - m.activeStyles().Base.GetHorizontalFrameSize()
580 return m.activeStyles().Description.Render(wrap(m.description.val, maxWidth))
581 }
582
583 func (m *MultiSelect[T]) renderOption(option Option[T], cursor, selected bool) string {
584 styles := m.activeStyles()
585 var parts []string
586 if cursor {
587 parts = append(parts, styles.MultiSelectSelector.String())
588 } else {
589 parts = append(parts, strings.Repeat(" ", lipgloss.Width(styles.MultiSelectSelector.String())))
590 }
591 if selected {
592 parts = append(parts, styles.SelectedPrefix.String())
593 parts = append(parts, styles.SelectedOption.Render(option.Key))
594 } else {
595 parts = append(parts, styles.UnselectedPrefix.String())
596 parts = append(parts, styles.UnselectedOption.Render(option.Key))
597 }
598 return lipgloss.JoinHorizontal(lipgloss.Left, parts...)
599 }
600
601 func (m *MultiSelect[T]) optionsView() (string, int, int) {
602 var sb strings.Builder
603
604 if m.options.loading && time.Since(m.options.loadingStart) > spinnerShowThreshold {
605 m.spinner.Style = m.activeStyles().MultiSelectSelector.UnsetString()
606 sb.WriteString(m.spinner.View() + " Loading...")
607 return sb.String(), -1, 1
608 }
609
610 var cursorOffset int
611 var cursorHeight int
612 for i, option := range m.filteredOptions {
613 cursor := m.cursor == i
614 line := m.renderOption(option, cursor, m.filteredOptions[i].selected)
615 if i < m.cursor {
616 cursorOffset += lipgloss.Height(line)
617 }
618 if cursor {
619 cursorHeight = lipgloss.Height(line)
620 }
621 sb.WriteString(line)
622 if i < len(m.options.val)-1 {
623 sb.WriteString("\n")
624 }
625 }
626
627 for i := len(m.filteredOptions); i < len(m.options.val)-1; i++ {
628 sb.WriteString("\n")
629 }
630
631 return sb.String(), cursorOffset, cursorHeight
632 }
633
634 // View renders the multi-select field.
635 func (m *MultiSelect[T]) View() string {
636 styles := m.activeStyles()
637
638 vpc, _, _ := m.optionsView()
639 m.viewport.SetContent(vpc)
640
641 var sb strings.Builder
642 if m.title.val != "" || m.title.fn != nil {
643 sb.WriteString(m.titleView())
644 sb.WriteString("\n")
645 }
646 if m.description.val != "" || m.description.fn != nil {
647 sb.WriteString(m.descriptionView() + "\n")
648 }
649 sb.WriteString(m.viewport.View())
650 return styles.Base.Width(m.width).Height(m.height).
651 Render(sb.String())
652 }
653
654 func (m *MultiSelect[T]) printOptions(w io.Writer) {
655 styles := m.activeStyles()
656 var sb strings.Builder
657 for i, option := range m.options.val {
658 if option.selected {
659 sb.WriteString(styles.SelectedOption.Render(fmt.Sprintf("%d. %s %s", i+1, "✓", option.Key)))
660 } else {
661 sb.WriteString(fmt.Sprintf("%d. %s", i+1, option.Key))
662 }
663 sb.WriteString("\n")
664 }
665 sb.WriteString("0. Confirm selection\n")
666 _, _ = fmt.Fprint(w, sb.String())
667 }
668
669 // setFilter sets the filter of the select field.
670 func (m *MultiSelect[T]) setFilter(filter bool) {
671 m.filtering = filter
672 m.keymap.SetFilter.SetEnabled(filter)
673 m.keymap.Filter.SetEnabled(!filter)
674 m.keymap.Next.SetEnabled(!filter)
675 m.keymap.Submit.SetEnabled(!filter)
676 m.keymap.Prev.SetEnabled(!filter)
677 m.keymap.ClearFilter.SetEnabled(!filter && m.filter.Value() != "")
678 }
679
680 // filterFunc returns true if the option matches the filter.
681 func (m *MultiSelect[T]) filterFunc(option string) bool {
682 // XXX: remove diacritics or allow customization of filter function.
683 return strings.Contains(strings.ToLower(option), strings.ToLower(m.filter.Value()))
684 }
685
686 // setSelectAllHelp enables the appropriate select all or select none keybinding.
687 func (m *MultiSelect[T]) setSelectAllHelp() {
688 if m.limit > 0 {
689 m.keymap.SelectAll.SetEnabled(false)
690 m.keymap.SelectNone.SetEnabled(false)
691 return
692 }
693
694 noneSelected := m.numFilteredSelected() <= 0
695 allSelected := m.numFilteredSelected() > 0 && m.numFilteredSelected() < len(m.filteredOptions)
696 selectAll := noneSelected || allSelected
697 m.keymap.SelectAll.SetEnabled(selectAll)
698 m.keymap.SelectNone.SetEnabled(!selectAll)
699 }
700
701 // Run runs the multi-select field.
702 func (m *MultiSelect[T]) Run() error {
703 if m.accessible { // TODO: remove in a future release.
704 return m.RunAccessible(os.Stdout, os.Stdin)
705 }
706 return Run(m)
707 }
708
709 // RunAccessible runs the multi-select field in accessible mode.
710 func (m *MultiSelect[T]) RunAccessible(w io.Writer, r io.Reader) error {
711 styles := m.activeStyles()
712 title := styles.Title.
713 PaddingRight(1).
714 Render(cmp.Or(m.title.val, "Select:"))
715 _, _ = fmt.Fprintln(w, title)
716 limit := m.limit
717 if limit == 0 {
718 limit = len(m.options.val)
719 }
720 _, _ = fmt.Fprintf(w, "Select up to %d options.\n", limit)
721
722 var choice int
723 for {
724 m.printOptions(w)
725
726 prompt := fmt.Sprintf("Input a number between %d and %d: ", 0, len(m.options.val))
727 choice = accessibility.PromptInt(w, r, prompt, 0, len(m.options.val), nil)
728 if choice <= 0 {
729 m.updateValue()
730 err := m.validate(m.accessor.Get())
731 if err != nil {
732 _, _ = fmt.Fprintln(w, err)
733 continue
734 }
735 break
736 }
737
738 if !m.options.val[choice-1].selected && m.limit > 0 && m.numSelected() >= m.limit {
739 _, _ = fmt.Fprintf(w, "You can't select more than %d options.\n", m.limit)
740 _, _ = fmt.Fprintln(w)
741 continue
742 }
743 m.options.val[choice-1].selected = !m.options.val[choice-1].selected
744 _, _ = fmt.Fprintln(w)
745 }
746
747 return nil
748 }
749
750 // WithTheme sets the theme of the multi-select field.
751 func (m *MultiSelect[T]) WithTheme(theme *Theme) Field {
752 if m.theme != nil {
753 return m
754 }
755 m.theme = theme
756 m.filter.Cursor.Style = theme.Focused.TextInput.Cursor
757 m.filter.Cursor.TextStyle = theme.Focused.TextInput.CursorText
758 m.filter.PromptStyle = theme.Focused.TextInput.Prompt
759 m.filter.TextStyle = theme.Focused.TextInput.Text
760 m.filter.PlaceholderStyle = theme.Focused.TextInput.Placeholder
761 m.updateViewportHeight()
762 return m
763 }
764
765 // WithKeyMap sets the keymap of the multi-select field.
766 func (m *MultiSelect[T]) WithKeyMap(k *KeyMap) Field {
767 m.keymap = k.MultiSelect
768 if !m.filterable {
769 m.keymap.Filter.SetEnabled(false)
770 m.keymap.ClearFilter.SetEnabled(false)
771 m.keymap.SetFilter.SetEnabled(false)
772 }
773 return m
774 }
775
776 // WithAccessible sets the accessible mode of the multi-select field.
777 //
778 // Deprecated: you may now call [MultiSelect.RunAccessible] directly to run the
779 // field in accessible mode.
780 func (m *MultiSelect[T]) WithAccessible(accessible bool) Field {
781 m.accessible = accessible
782 return m
783 }
784
785 // WithWidth sets the width of the multi-select field.
786 func (m *MultiSelect[T]) WithWidth(width int) Field {
787 m.width = width
788 return m
789 }
790
791 // WithHeight sets the total height of the multi-select field. Including padding
792 // and help menu heights.
793 func (m *MultiSelect[T]) WithHeight(height int) Field {
794 m.Height(height)
795 return m
796 }
797
798 // WithPosition sets the position of the multi-select field.
799 func (m *MultiSelect[T]) WithPosition(p FieldPosition) Field {
800 if m.filtering {
801 return m
802 }
803 m.keymap.Prev.SetEnabled(!p.IsFirst())
804 m.keymap.Next.SetEnabled(!p.IsLast())
805 m.keymap.Submit.SetEnabled(p.IsLast())
806 return m
807 }
808
809 // GetKey returns the multi-select's key.
810 func (m *MultiSelect[T]) GetKey() string {
811 return m.key
812 }
813
814 // GetValue returns the multi-select's value.
815 func (m *MultiSelect[T]) GetValue() any {
816 return m.accessor.Get()
817 }
818
819 // GetFiltering returns whether the multi-select is filtering.
820 func (m *MultiSelect[T]) GetFiltering() bool {
821 return m.filtering
822 }