internal/selection_menu.go

138 lines · 3418 bytes

  1package internal
  2
  3import (
  4	"fmt"
  5	"strings"
  6	tea "github.com/charmbracelet/bubbletea"
  7)
  8
  9// SelectionOption holds the label and the internal key
 10type SelectionOption struct {
 11    Label string
 12    Key   string
 13}
 14
 15// Model represents the application state for the selection prompt
 16type Model struct {
 17	options      map[string]string // Now using a map for options
 18	filter       string
 19	filteredKeys []SelectionOption
 20	selected     int
 21}
 22
 23// Init initializes the model
 24func (m Model) Init() tea.Cmd {
 25	return nil
 26}
 27
 28// Update handles user input and updates the model
 29func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 30	// Only filter options if a key press modifies the filter
 31	updateFilter := false
 32
 33	switch msg := msg.(type) {
 34	case tea.KeyMsg:
 35		switch msg.String() {
 36		case "ctrl+c", "q":
 37			return m, tea.Quit
 38		case "backspace":
 39			if len(m.filter) > 0 {
 40				m.filter = m.filter[:len(m.filter)-1]
 41				updateFilter = true // Mark for updating the filter
 42			}
 43		case "down":
 44			// Move cursor down within bounds
 45			if m.selected < len(m.filteredKeys)-1 {
 46				m.selected++
 47			}
 48		case "up":
 49			// Move cursor up within bounds
 50			if m.selected > 0 {
 51				m.selected--
 52			}
 53		case "enter":
 54			return m, tea.Quit // Or return the selected option
 55		default:
 56			if msg.String() != "" {
 57				m.filter += msg.String()
 58				updateFilter = true // Mark for updating the filter
 59			}
 60		}
 61	}
 62
 63	// Only filter options if the filter was actually modified
 64	if updateFilter {
 65		m.filterOptions()
 66		// Reset selected index after filtering
 67		m.selected = 0
 68	}
 69
 70	return m, nil
 71}
 72
 73
 74// View renders the UI
 75func (m Model) View() string {
 76	var b strings.Builder
 77
 78	b.WriteString("Search (Press Ctrl+C to quit):\n\n")
 79	b.WriteString("Filter: " + m.filter + "\n\n")
 80
 81	if len(m.filteredKeys) == 0 {
 82		b.WriteString("No matches found.\n")
 83	} else {
 84		for i, option := range m.filteredKeys {
 85			if i == m.selected {
 86				b.WriteString(fmt.Sprintf("▶ %s\n", option.Label))
 87			} else {
 88				b.WriteString(fmt.Sprintf("  %s\n", option.Label))
 89			}
 90		}
 91	}
 92
 93	return b.String()
 94}
 95
 96// filterOptions filters options based on the search term
 97func (m *Model) filterOptions() {
 98	m.filteredKeys = nil
 99	for key, value := range m.options {
100		if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) { // Check values instead of keys
101			m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key}) // Set Label to value
102		}
103	}
104}
105
106// DynamicSelect displays a full-screen selection prompt with search
107func DynamicSelect(options map[string]string) (SelectionOption, error) {
108	ClearScreen()
109	defer RestoreScreen()
110	model := &Model{ // Use a pointer to Model
111		options: options,
112		filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
113	}
114
115	// Populate filteredKeys initially
116	model.filterOptions()
117
118	// Create a new Program instance
119	p := tea.NewProgram(model)
120
121	// Run the program and capture the final model and any error
122	finalModel, err := p.Run()
123	if err != nil {
124		return SelectionOption{}, err
125	}
126
127	// Type assert to get the specific model type
128	finalSelectionModel, ok := finalModel.(*Model)
129	if !ok {
130		return SelectionOption{}, fmt.Errorf("unexpected model type")
131	}
132
133	// Return the selected option after quitting
134	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
135		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
136	}
137	return SelectionOption{}, nil
138}