internal/selection_menu.go

195 lines · 5181 bytes

  1package internal
  2
  3import (
  4	"fmt"
  5	"sort"
  6	"strings"
  7
  8	tea "github.com/charmbracelet/bubbletea"
  9)
 10
 11// SelectionOption holds the label and the internal key
 12type SelectionOption struct {
 13	Label string
 14	Key   string
 15}
 16
 17// Model represents the application state for the selection prompt
 18type Model struct {
 19	options        map[string]string
 20	filter         string
 21	filteredKeys   []SelectionOption
 22	selected       int
 23	terminalWidth  int
 24	terminalHeight int
 25	scrollOffset   int // Track the topmost visible item
 26}
 27
 28// Init initializes the model
 29func (m Model) Init() tea.Cmd {
 30	return nil
 31}
 32
 33// Update handles user input and updates the model
 34func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 35	// Handle terminal resize messages
 36	if wsm, ok := msg.(tea.WindowSizeMsg); ok {
 37		m.terminalWidth = wsm.Width
 38		m.terminalHeight = wsm.Height
 39	}
 40
 41	updateFilter := false
 42
 43	switch msg := msg.(type) {
 44	case tea.KeyMsg:
 45		switch msg.String() {
 46		case "ctrl+c", "q":
 47			// Return quit selection option instead of quitting the program
 48			m.filteredKeys[m.selected] = SelectionOption{"quit", "-1"}
 49			return m, tea.Quit // Properly exit the program
 50		case "backspace":
 51			if len(m.filter) > 0 {
 52				m.filter = m.filter[:len(m.filter)-1]
 53				updateFilter = true
 54			}
 55		case "down":
 56			// Move the selection cursor down
 57			if m.selected < len(m.filteredKeys)-1 {
 58				m.selected++
 59			}
 60
 61			// Scroll the view if necessary
 62			if m.selected >= m.scrollOffset+m.visibleItemsCount() {
 63				m.scrollOffset++
 64			}
 65		case "up":
 66			// Move the selection cursor up
 67			if m.selected > 0 {
 68				m.selected--
 69			}
 70
 71			// Scroll the view if necessary
 72			if m.selected < m.scrollOffset {
 73				m.scrollOffset--
 74			}
 75		case "enter":
 76			if m.filteredKeys[m.selected].Key == "add_new" {
 77				fmt.Println("Adding a new anime...")
 78				m.filteredKeys[m.selected] = SelectionOption{"add_new", "0"}
 79				return m, tea.Quit
 80			}
 81			return m, tea.Quit
 82		default:
 83			if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
 84				m.filter += msg.String()
 85				updateFilter = true
 86			}
 87		}
 88	}
 89
 90	if updateFilter {
 91		m.filterOptions()
 92		m.selected = 0     // Reset selection to the first item after filtering
 93		m.scrollOffset = 0 // Reset scrolling
 94	}
 95
 96	return m, nil
 97}
 98
 99// View renders the UI and only shows as many options as fit in the terminal
100func (m Model) View() string {
101	var b strings.Builder
102
103	// Display the search prompt and filter
104	b.WriteString("Search (Press Ctrl+C to quit):\n")
105	b.WriteString("Filter: " + m.filter + "\n")
106
107	if len(m.filteredKeys) == 0 {
108		b.WriteString("\nNo matches found.\n")
109	} else {
110		visibleItems := m.visibleItemsCount()
111
112		// Determine the slice of items to display based on scroll offset
113		start := m.scrollOffset
114		end := start + visibleItems
115		if end > len(m.filteredKeys) {
116			end = len(m.filteredKeys)
117		}
118
119		// Render the options within the visible range
120		for i := start; i < end; i++ {
121			if i == m.selected {
122				b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
123			} else {
124				b.WriteString(fmt.Sprintf("  %s\n", m.filteredKeys[i].Label)) // Regular option
125			}
126		}
127	}
128
129	return b.String()
130}
131
132// visibleItemsCount calculates how many options fit in the terminal
133func (m Model) visibleItemsCount() int {
134	// Leave space for the filter and other UI elements
135	return m.terminalHeight - 4 // Adjust this number based on your terminal layout
136}
137
138// filterOptions filters and sorts options based on the search term
139func (m *Model) filterOptions() {
140	m.filteredKeys = []SelectionOption{}
141
142	for key, value := range m.options {
143		// When the key is " ", compare and display using the value instead
144		if key == " " {
145			if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
146				m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
147			}
148		} else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
149			m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
150		}
151	}
152
153	// Sort the filtered options alphabetically
154	sort.Slice(m.filteredKeys, func(i, j int) bool {
155		return m.filteredKeys[i].Label < m.filteredKeys[j].Label
156	})
157
158	// Reset the selection to the "Add new anime" option if no matches are found
159	if len(m.filteredKeys) == 0 {
160		m.filteredKeys = append(m.filteredKeys, SelectionOption{
161			Label: "Add new anime",
162			Key:   "add_new",
163		})
164	}
165	m.filteredKeys = append(m.filteredKeys, SelectionOption{
166		Label: "Quit",
167		Key:   "-1",
168	})
169}
170
171// DynamicSelect displays a simple selection prompt without extra features
172func DynamicSelect(options map[string]string) (SelectionOption, error) {
173	model := &Model{
174		options:      options,
175		filteredKeys: make([]SelectionOption, 0),
176	}
177
178	model.filterOptions()
179	p := tea.NewProgram(model)
180
181	finalModel, err := p.Run()
182	if err != nil {
183		return SelectionOption{}, err
184	}
185
186	finalSelectionModel, ok := finalModel.(*Model)
187	if !ok {
188		return SelectionOption{}, fmt.Errorf("unexpected model type")
189	}
190
191	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
192		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
193	}
194	return SelectionOption{}, nil
195}