internal/selection_menu.go
256 lines · 6833 bytes
1package internal
2
3import (
4 "bytes"
5 "fmt"
6 "os/exec"
7 "sort"
8 "strings"
9
10 tea "github.com/charmbracelet/bubbletea"
11)
12
13// SelectionOption holds the label and the internal key
14type SelectionOption struct {
15 Label string
16 Key string
17}
18
19// Model represents the application state for the selection prompt
20type Model struct {
21 options map[string]string
22 filter string
23 filteredKeys []SelectionOption
24 selected int
25 terminalWidth int
26 terminalHeight int
27 scrollOffset int // Track the topmost visible item
28}
29
30// Init initializes the model
31func (m Model) Init() tea.Cmd {
32 return nil
33}
34
35// Update handles user input and updates the model
36func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
37 // Handle terminal resize messages
38 if wsm, ok := msg.(tea.WindowSizeMsg); ok {
39 m.terminalWidth = wsm.Width
40 m.terminalHeight = wsm.Height
41 }
42
43 updateFilter := false
44
45 switch msg := msg.(type) {
46 case tea.KeyMsg:
47 switch msg.String() {
48 case "ctrl+c", "q":
49 // Return quit selection option instead of quitting the program
50 m.filteredKeys[m.selected] = SelectionOption{"quit", "-1"}
51 return m, tea.Quit // Properly exit the program
52 case "backspace":
53 if len(m.filter) > 0 {
54 m.filter = m.filter[:len(m.filter)-1]
55 updateFilter = true
56 }
57 case "down":
58 // Move the selection cursor down
59 if m.selected < len(m.filteredKeys)-1 {
60 m.selected++
61 }
62
63 // Scroll the view if necessary
64 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
65 m.scrollOffset++
66 }
67 case "up":
68 // Move the selection cursor up
69 if m.selected > 0 {
70 m.selected--
71 }
72
73 // Scroll the view if necessary
74 if m.selected < m.scrollOffset {
75 m.scrollOffset--
76 }
77 case "enter":
78 if m.filteredKeys[m.selected].Key == "add_new" {
79 CurdOut("Adding a new anime...")
80 m.filteredKeys[m.selected] = SelectionOption{"add_new", "0"}
81 return m, tea.Quit
82 }
83 return m, tea.Quit
84 default:
85 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
86 m.filter += msg.String()
87 updateFilter = true
88 }
89 }
90 }
91
92 if updateFilter {
93 m.filterOptions()
94 m.selected = 0 // Reset selection to the first item after filtering
95 m.scrollOffset = 0 // Reset scrolling
96 }
97
98 return m, nil
99}
100
101// View renders the UI and only shows as many options as fit in the terminal
102func (m Model) View() string {
103 var b strings.Builder
104
105 // Display the search prompt and filter
106 b.WriteString("Search (Press Ctrl+C to quit):\n")
107 b.WriteString("Filter: " + m.filter + "\n")
108
109 if len(m.filteredKeys) == 0 {
110 b.WriteString("\nNo matches found.\n")
111 } else {
112 visibleItems := m.visibleItemsCount()
113
114 // Determine the slice of items to display based on scroll offset
115 start := m.scrollOffset
116 end := start + visibleItems
117 if end > len(m.filteredKeys) {
118 end = len(m.filteredKeys)
119 }
120
121 // Render the options within the visible range
122 for i := start; i < end; i++ {
123 if i == m.selected {
124 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
125 } else {
126 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label)) // Regular option
127 }
128 }
129 }
130
131 return b.String()
132}
133
134// visibleItemsCount calculates how many options fit in the terminal
135func (m Model) visibleItemsCount() int {
136 // Leave space for the filter and other UI elements
137 return m.terminalHeight - 4 // Adjust this number based on your terminal layout
138}
139
140// filterOptions filters and sorts options based on the search term
141func (m *Model) filterOptions() {
142 m.filteredKeys = []SelectionOption{}
143
144 for key, value := range m.options {
145 // When the key is " ", compare and display using the value instead
146 if key == " " {
147 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
148 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
149 }
150 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
151 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
152 }
153 }
154
155 // Sort the filtered options alphabetically
156 sort.Slice(m.filteredKeys, func(i, j int) bool {
157 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
158 })
159
160 // Reset the selection to the "Add new anime" option if no matches are found
161 if len(m.filteredKeys) == 0 {
162 m.filteredKeys = append(m.filteredKeys, SelectionOption{
163 Label: "Add new anime",
164 Key: "add_new",
165 })
166 }
167 m.filteredKeys = append(m.filteredKeys, SelectionOption{
168 Label: "Quit",
169 Key: "-1",
170 })
171}
172
173func RofiSelect(options map[string]string) (SelectionOption, error) {
174 // Create a slice to store the options in the order we want
175 var optionsList []string
176 for _, value := range options {
177 optionsList = append(optionsList, value)
178 }
179
180 // Sort the options alphabetically
181 sort.Strings(optionsList)
182
183 // Add "Add new anime" and "Quit" options
184 optionsList = append(optionsList, "Add new anime", "Quit")
185
186 // Join all options into a single string, separated by newlines
187 optionsString := strings.Join(optionsList, "\n")
188
189 // Prepare the Rofi command
190 cmd := exec.Command("rofi", "-dmenu", "-i", "-p", "Select an anime")
191
192 // Set up pipes for input and output
193 cmd.Stdin = strings.NewReader(optionsString)
194 var out bytes.Buffer
195 cmd.Stdout = &out
196
197 // Run the command
198 err := cmd.Run()
199 if err != nil {
200 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
201 }
202
203 // Get the selected option
204 selected := strings.TrimSpace(out.String())
205
206 // Handle special cases
207 switch selected {
208 case "":
209 return SelectionOption{}, fmt.Errorf("no selection made")
210 case "Add new anime":
211 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
212 case "Quit":
213 return SelectionOption{Label: "Quit", Key: "-1"}, nil
214 }
215
216 // Find the key for the selected value
217 for key, value := range options {
218 if value == selected {
219 return SelectionOption{Label: value, Key: key}, nil
220 }
221 }
222
223 // If we get here, the selected option wasn't found in the original map
224 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
225}
226
227// DynamicSelect displays a simple selection prompt without extra features
228func DynamicSelect(options map[string]string) (SelectionOption, error) {
229
230 if GetGlobalConfig().RofiSelection {
231 return RofiSelect(options)
232 }
233
234 model := &Model{
235 options: options,
236 filteredKeys: make([]SelectionOption, 0),
237 }
238
239 model.filterOptions()
240 p := tea.NewProgram(model)
241
242 finalModel, err := p.Run()
243 if err != nil {
244 return SelectionOption{}, err
245 }
246
247 finalSelectionModel, ok := finalModel.(*Model)
248 if !ok {
249 return SelectionOption{}, fmt.Errorf("unexpected model type")
250 }
251
252 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
253 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
254 }
255 return SelectionOption{}, nil
256}