internal/selection_menu.go

181 lines · 5117 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	terminalHeight int // New field to hold the terminal height
 22}
 23
 24// Init initializes the model
 25func (m Model) Init() tea.Cmd {
 26	return nil
 27}
 28
 29// Update handles user input and updates the model
 30func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 31	// Handle terminal resize messages
 32	if wsm, ok := msg.(tea.WindowSizeMsg); ok {
 33		m.terminalHeight = wsm.Height // Get the terminal height
 34	}
 35
 36	// Only filter options if a key press modifies the filter
 37	updateFilter := false
 38
 39	switch msg := msg.(type) {
 40	case tea.KeyMsg:
 41		switch msg.String() {
 42		case "ctrl+c", "q":
 43			return m, tea.Quit
 44		case "backspace":
 45			if len(m.filter) > 0 {
 46				m.filter = m.filter[:len(m.filter)-1]
 47				updateFilter = true // Mark for updating the filter
 48			}
 49		case "down":
 50			// Move cursor down within bounds
 51			if m.selected < len(m.filteredKeys)-1 {
 52				m.selected++
 53			}
 54		case "up":
 55			// Move cursor up within bounds
 56			if m.selected > 0 {
 57				m.selected--
 58			}
 59		case "enter":
 60            // If "Add new anime" is selected, handle it here
 61            if m.filteredKeys[m.selected].Key == "add_new" {
 62                // Implement your logic for adding a new anime
 63                fmt.Println("Adding a new anime...") // Temporary print statement
 64                return m, tea.Quit
 65            }
 66            return m, tea.Quit // Or return the selected option for other cases
 67        default:
 68			if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
 69				m.filter += msg.String()
 70				updateFilter = true // Mark for updating the filter
 71			}
 72		}
 73	}
 74
 75	// Only filter options if the filter was actually modified
 76	if updateFilter {
 77		m.filterOptions()
 78		// Reset selected index after filtering
 79		m.selected = 0
 80	}
 81
 82	return m, nil
 83}
 84
 85// View renders the UI
 86func (m Model) View() string {
 87    var b strings.Builder
 88
 89    b.WriteString("Search (Press Ctrl+C to quit):\n\n")
 90    b.WriteString("Filter: " + m.filter + "\n\n")
 91
 92    if len(m.filteredKeys) == 0 {
 93        b.WriteString("No matches found.\n")
 94    } else {
 95        // Determine how many entries can fit in the terminal
 96        maxEntries := m.terminalHeight - 4 // Adjust for header and padding
 97        if maxEntries < 1 {
 98            maxEntries = 1 // At least show one option
 99        }
100
101        // Limit the number of displayed entries
102        start := m.selected
103        if start >= len(m.filteredKeys) {
104            start = len(m.filteredKeys) - 1
105        }
106        end := start + maxEntries
107        if end > len(m.filteredKeys) {
108            end = len(m.filteredKeys)
109        }
110        if start > end {
111            start = end
112        }
113
114        // Display the filtered keys with selection indicator
115        for i := start; i < end; i++ {
116            if i == m.selected {
117                b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label))
118            } else {
119                b.WriteString(fmt.Sprintf("  %s\n", m.filteredKeys[i].Label))
120            }
121        }
122    }
123
124    return b.String()
125}
126
127
128// filterOptions filters options based on the search term
129func (m *Model) filterOptions() {
130    // Clear the filteredKeys slice before appending new matches
131    m.filteredKeys = []SelectionOption{}
132
133    for key, value := range m.options {
134        if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
135            m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
136        }
137    }
138
139    // If no matches were found, add the "Add new anime" option
140    if len(m.filteredKeys) == 0 {
141        m.filteredKeys = append(m.filteredKeys, SelectionOption{
142            Label: "Add new anime",
143            Key:   "add_new", // Special key to identify this option
144        })
145    }
146}
147
148
149// DynamicSelect displays a full-screen selection prompt with search
150func DynamicSelect(options map[string]string) (SelectionOption, error) {
151	// ClearScreen()
152	// defer RestoreScreen()
153	model := &Model{ // Use a pointer to Model
154		options: options,
155		filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
156	}
157
158	// Populate filteredKeys initially
159	model.filterOptions()
160
161	// Create a new Program instance
162	p := tea.NewProgram(model)
163
164	// Run the program and capture the final model and any error
165	finalModel, err := p.Run()
166	if err != nil {
167		return SelectionOption{}, err
168	}
169
170	// Type assert to get the specific model type
171	finalSelectionModel, ok := finalModel.(*Model)
172	if !ok {
173		return SelectionOption{}, fmt.Errorf("unexpected model type")
174	}
175
176	// Return the selected option after quitting
177	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
178		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
179	}
180	return SelectionOption{}, nil
181}