internal/selection_menu.go
188 lines · 4857 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 m, tea.Quit
48 case "backspace":
49 if len(m.filter) > 0 {
50 m.filter = m.filter[:len(m.filter)-1]
51 updateFilter = true
52 }
53 case "down":
54 // Move the selection cursor down
55 if m.selected < len(m.filteredKeys)-1 {
56 m.selected++
57 }
58
59 // Scroll the view if necessary
60 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
61 m.scrollOffset++
62 }
63 case "up":
64 // Move the selection cursor up
65 if m.selected > 0 {
66 m.selected--
67 }
68
69 // Scroll the view if necessary
70 if m.selected < m.scrollOffset {
71 m.scrollOffset--
72 }
73 case "enter":
74 if m.filteredKeys[m.selected].Key == "add_new" {
75 fmt.Println("Adding a new anime...")
76 return m, tea.Quit
77 }
78 return m, tea.Quit
79 default:
80 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
81 m.filter += msg.String()
82 updateFilter = true
83 }
84 }
85 }
86
87 if updateFilter {
88 m.filterOptions()
89 m.selected = 0 // Reset selection to the first item after filtering
90 m.scrollOffset = 0 // Reset scrolling
91 }
92
93 return m, nil
94}
95
96// View renders the UI and only shows as many options as fit in the terminal
97func (m Model) View() string {
98 var b strings.Builder
99
100 // Display the search prompt and filter
101 b.WriteString("Search (Press Ctrl+C to quit):\n")
102 b.WriteString("Filter: " + m.filter + "\n")
103
104 if len(m.filteredKeys) == 0 {
105 b.WriteString("\nNo matches found.\n")
106 } else {
107 visibleItems := m.visibleItemsCount()
108
109 // Determine the slice of items to display based on scroll offset
110 start := m.scrollOffset
111 end := start + visibleItems
112 if end > len(m.filteredKeys) {
113 end = len(m.filteredKeys)
114 }
115
116 // Render the options within the visible range
117 for i := start; i < end; i++ {
118 if i == m.selected {
119 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
120 } else {
121 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label)) // Regular option
122 }
123 }
124 }
125
126 return b.String()
127}
128
129// visibleItemsCount calculates how many options fit in the terminal
130func (m Model) visibleItemsCount() int {
131 // Leave space for the filter and other UI elements
132 return m.terminalHeight - 4 // Adjust this number based on your terminal layout
133}
134
135// filterOptions filters and sorts options based on the search term
136func (m *Model) filterOptions() {
137 m.filteredKeys = []SelectionOption{}
138
139 for key, value := range m.options {
140 // When the key is " ", compare and display using the value instead
141 if key == " " {
142 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
143 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
144 }
145 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
146 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
147 }
148 }
149
150 // Sort the filtered options alphabetically
151 sort.Slice(m.filteredKeys, func(i, j int) bool {
152 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
153 })
154
155 // Reset the selection to the "Add new anime" option if no matches are found
156 if len(m.filteredKeys) == 0 {
157 m.filteredKeys = append(m.filteredKeys, SelectionOption{
158 Label: "Add new anime",
159 Key: "add_new",
160 })
161 }
162}
163
164// DynamicSelect displays a simple selection prompt without extra features
165func DynamicSelect(options map[string]string) (SelectionOption, error) {
166 model := &Model{
167 options: options,
168 filteredKeys: make([]SelectionOption, 0),
169 }
170
171 model.filterOptions()
172 p := tea.NewProgram(model)
173
174 finalModel, err := p.Run()
175 if err != nil {
176 return SelectionOption{}, err
177 }
178
179 finalSelectionModel, ok := finalModel.(*Model)
180 if !ok {
181 return SelectionOption{}, fmt.Errorf("unexpected model type")
182 }
183
184 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
185 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
186 }
187 return SelectionOption{}, nil
188}