picker.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package picker
  2. import (
  3. "github.com/rivo/tview"
  4. "github.com/sahilm/fuzzy"
  5. )
  6. type Picker struct {
  7. *tview.Flex
  8. Input *tview.InputField
  9. List *tview.List
  10. app *tview.Application
  11. items Items
  12. }
  13. func New(app *tview.Application, items Items) *Picker {
  14. p := &Picker{
  15. Flex: tview.NewFlex(),
  16. Input: tview.NewInputField(),
  17. List: tview.NewList(),
  18. app: app,
  19. items: items,
  20. }
  21. // Render all of the items initially.
  22. p.changed("")
  23. p.Input.SetChangedFunc(p.changed)
  24. p.List.ShowSecondaryText(false).SetFocusFunc(func() {
  25. app.SetFocus(p.Input)
  26. })
  27. p.Flex.
  28. SetDirection(tview.FlexRow).
  29. AddItem(p.Input, 3, 1, true).
  30. AddItem(p.List, 0, 1, false)
  31. return p
  32. }
  33. func (p *Picker) changed(text string) {
  34. var fuzzied Items
  35. if text == "" {
  36. fuzzied = append(fuzzied, p.items...)
  37. } else {
  38. matches := fuzzy.FindFrom(text, p.items)
  39. for _, match := range matches {
  40. fuzzied = append(fuzzied, p.items[match.Index])
  41. }
  42. }
  43. p.List.Clear()
  44. for _, item := range fuzzied {
  45. p.List.AddItem(item.text, "", 0, item.selected)
  46. }
  47. }