internal/selection_menu.go
782 lines · 20561 bytes
1package internal
2
3import (
4 "bytes"
5 "crypto/md5"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "reflect"
13 "sort"
14 "strings"
15 "time"
16
17 tea "github.com/charmbracelet/bubbletea"
18 "github.com/charmbracelet/lipgloss"
19)
20
21// Model represents the application state for the selection prompt
22type Model struct {
23 filter string
24 filteredKeys []SelectionOption
25 allOptions []SelectionOption
26 selected int
27 terminalWidth int
28 terminalHeight int
29 scrollOffset int
30 addNewOption bool
31 isHomeMenu bool // If true, ESC quits; if false, ESC goes back
32}
33
34type optionsRefreshedMsg struct {
35 options []SelectionOption
36}
37
38type SelectionRefreshConfig struct {
39 Updates <-chan AnimeList
40 BuildOptions func(AnimeList) []SelectionOption
41}
42
43type PreviewSelectionRefreshConfig struct {
44 Updates <-chan AnimeList
45 BuildOptions func(AnimeList) map[string]RofiSelectPreview
46}
47
48var (
49 // Style definitions
50 titleStyle = lipgloss.NewStyle().
51 Foreground(lipgloss.Color("#7CB9E8")). // Light blue
52 Bold(true)
53
54 filterLabelStyle = lipgloss.NewStyle().
55 Foreground(lipgloss.Color("#FF69B4")). // Hot pink
56 Bold(true)
57
58 filterTextStyle = lipgloss.NewStyle().
59 Foreground(lipgloss.Color("#98FB98")) // Pale green
60
61 selectedItemStyle = lipgloss.NewStyle().
62 Foreground(lipgloss.Color("#FFFFFF")). // White text
63 Background(lipgloss.Color("#4A90E2")). // Softer blue background
64 Bold(true).
65 Padding(0, 1).
66 Border(lipgloss.NormalBorder(), false, false, false, true). // Left border only
67 BorderForeground(lipgloss.Color("#FFFFFF")) // White border
68
69 regularItemStyle = lipgloss.NewStyle().
70 Foreground(lipgloss.Color("#E6E6FA")). // Light lavender
71 Padding(0, 1)
72
73 noMatchesStyle = lipgloss.NewStyle().
74 Foreground(lipgloss.Color("#FF6B6B")). // Coral red
75 Italic(true)
76
77 quitHintStyle = lipgloss.NewStyle().
78 Foreground(lipgloss.Color("#FFD700")) // Gold
79)
80
81// Init initializes the model
82func (m Model) Init() tea.Cmd {
83 return nil
84}
85
86// Update handles user input and updates the model
87func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
88 // Handle terminal resize messages
89 if wsm, ok := msg.(tea.WindowSizeMsg); ok {
90 m.terminalWidth = wsm.Width
91 m.terminalHeight = wsm.Height
92 }
93
94 updateFilter := false
95
96 switch msg := msg.(type) {
97 case optionsRefreshedMsg:
98 m.replaceOptions(msg.options)
99 return m, nil
100 case tea.KeyMsg:
101 switch msg.String() {
102 case "ctrl+c":
103 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
104 m.selected = 0
105 return m, tea.Quit
106 case "esc":
107 // ESC: quit on home menu, go back on sub-menus
108 if m.isHomeMenu {
109 // Quit
110 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
111 m.selected = 0
112 } else {
113 // Go back
114 m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
115 m.selected = 0
116 }
117 return m, tea.Quit
118 case "backspace":
119 if len(m.filter) > 0 {
120 m.filter = m.filter[:len(m.filter)-1]
121 updateFilter = true
122 }
123 case "down", "tab", "ctrl+n":
124 // Move the selection cursor down
125 if m.selected < len(m.filteredKeys)-1 {
126 m.selected++
127 }
128
129 // Scroll the view if necessary
130 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
131 m.scrollOffset++
132 }
133 case "up", "shift+tab", "ctrl+p":
134 // Move the selection cursor up
135 if m.selected > 0 {
136 m.selected--
137 }
138
139 // Scroll the view if necessary
140 if m.selected < m.scrollOffset {
141 m.scrollOffset--
142 }
143 case "enter":
144 if len(m.filteredKeys) == 0 {
145 return m, nil
146 }
147 if m.filteredKeys[m.selected].Key == "add_new" {
148 CurdOut("Adding a new anime...")
149 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
150 return m, tea.Quit
151 }
152 return m, tea.Quit
153 default:
154 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
155 m.filter += msg.String()
156 updateFilter = true
157 }
158 }
159 }
160
161 if updateFilter {
162 m.filterOptions()
163 m.selected = 0 // Reset selection to the first item after filtering
164 m.scrollOffset = 0 // Reset scrolling
165 }
166
167 return m, nil
168}
169
170func (m *Model) replaceOptions(options []SelectionOption) {
171 previousIndex := m.selected
172 previousKey := ""
173 previousLabel := ""
174
175 if m.selected >= 0 && m.selected < len(m.filteredKeys) {
176 previousKey = m.filteredKeys[m.selected].Key
177 previousLabel = m.filteredKeys[m.selected].Label
178 }
179
180 m.allOptions = options
181 m.filterOptions()
182
183 if len(m.filteredKeys) == 0 {
184 m.selected = 0
185 m.scrollOffset = 0
186 return
187 }
188
189 m.selected = findSelectionIndex(m.filteredKeys, previousKey, previousLabel, previousIndex)
190 if m.selected < 0 {
191 m.selected = 0
192 }
193
194 if m.selected < m.scrollOffset {
195 m.scrollOffset = m.selected
196 }
197
198 visibleCount := m.visibleItemsCount()
199 if visibleCount <= 0 {
200 m.scrollOffset = 0
201 return
202 }
203
204 if m.selected >= m.scrollOffset+visibleCount {
205 m.scrollOffset = m.selected - visibleCount + 1
206 }
207 if m.scrollOffset < 0 {
208 m.scrollOffset = 0
209 }
210}
211
212// View renders the UI and only shows as many options as fit in the terminal
213func (m Model) View() string {
214 var b strings.Builder
215
216 // Display the search prompt and filter with colors
217 b.WriteString(titleStyle.Render("Search") + " (Press " +
218 quitHintStyle.Render("Ctrl+C") + " to quit):\n")
219
220 b.WriteString(filterLabelStyle.Render("Filter: ") +
221 filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing
222
223 if len(m.filteredKeys) == 0 {
224 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
225 } else {
226 visibleItems := m.visibleItemsCount()
227 start := m.scrollOffset
228 end := start + visibleItems
229 if end > len(m.filteredKeys) {
230 end = len(m.filteredKeys)
231 }
232
233 // Render the options within the visible range
234 for i := start; i < end; i++ {
235 if i == m.selected {
236 b.WriteString(selectedItemStyle.Render(m.filteredKeys[i].Label) + "\n")
237 } else {
238 b.WriteString(regularItemStyle.Render(m.filteredKeys[i].Label) + "\n")
239 }
240 }
241 }
242
243 return b.String()
244}
245
246// visibleItemsCount calculates how many options fit in the terminal
247func (m Model) visibleItemsCount() int {
248 // Leave space for the filter and other UI elements
249 count := m.terminalHeight - 4 // Adjust this number based on your terminal layout
250 if count < 1 {
251 return 1
252 }
253 return count
254}
255
256// filterOptions filters and sorts options based on the search term
257func (m *Model) filterOptions() {
258 m.filteredKeys = nil
259 for _, opt := range m.allOptions {
260 if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
261 m.filteredKeys = append(m.filteredKeys, opt)
262 }
263 }
264
265 // Sort the filtered options alphabetically unless this is a menu selection
266 isMenu := false
267 for _, opt := range m.allOptions {
268 if opt.Key == "ALL" || opt.Key == "CURRENT" {
269 isMenu = true
270 break
271 }
272 }
273
274 if !isMenu {
275 sort.Slice(m.filteredKeys, func(i, j int) bool {
276 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
277 })
278 }
279
280 // Determine whether the current filter is a substring of the pinned labels.
281 // When the filter matches "back" (e.g. "b", "ba", "bac", "back"), Back should
282 // appear BEFORE "Add new anime" so it is easy to reach. Otherwise keep the
283 // default order: Add new anime → Back → Quit.
284 // All three pinned items are always shown regardless of filter text.
285 filterLower := strings.ToLower(m.filter)
286 backMatchesFilter := filterLower != "" && strings.Contains("back", filterLower)
287
288 // If filter targets "back", pin it above Add new anime
289 if !m.isHomeMenu && backMatchesFilter {
290 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
291 }
292
293 // Add new anime is always shown (pinned)
294 if m.addNewOption {
295
296 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
297 }
298
299 // Back in its default position (after Add new anime) when filter doesn't target it
300 if !m.isHomeMenu && !backMatchesFilter {
301 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
302 }
303
304 // Quit is always last
305 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
306}
307
308func detectHomeMenu(options []SelectionOption) bool {
309 for _, opt := range options {
310 if opt.Key == "ALL" || opt.Key == "CURRENT" {
311 return true
312 }
313 }
314 return false
315}
316
317func findSelectionIndex(options []SelectionOption, previousKey string, previousLabel string, fallbackIndex int) int {
318 if previousKey != "" {
319 for idx, option := range options {
320 if option.Key == previousKey {
321 return idx
322 }
323 }
324 }
325
326 if previousLabel != "" {
327 for idx, option := range options {
328 if option.Label == previousLabel {
329 return idx
330 }
331 }
332 }
333
334 if fallbackIndex >= 0 && fallbackIndex < len(options) {
335 return fallbackIndex
336 }
337
338 if len(options) == 0 {
339 return -1
340 }
341
342 return min(fallbackIndex, len(options)-1)
343}
344
345func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
346 config := GetGlobalConfig()
347 if config == nil || strings.TrimSpace(config.MenuOrder) == "" {
348 return options
349 }
350
351 menuOrder := strings.Split(config.MenuOrder, ",")
352 optMap := make(map[string]SelectionOption)
353 for _, opt := range options {
354 optMap[opt.Key] = opt
355 }
356
357 sorted := make([]SelectionOption, 0, len(options))
358 for _, key := range menuOrder {
359 if opt, exists := optMap[key]; exists {
360 sorted = append(sorted, opt)
361 delete(optMap, key)
362 }
363 }
364
365 for _, opt := range options {
366 if _, exists := optMap[opt.Key]; exists {
367 sorted = append(sorted, opt)
368 delete(optMap, opt.Key)
369 }
370 }
371
372 return sorted
373}
374
375func previewOptionsToSortedSelection(options map[string]RofiSelectPreview) []SelectionOption {
376 selectionOptions := make([]SelectionOption, 0, len(options))
377 for id, opt := range options {
378 selectionOptions = append(selectionOptions, SelectionOption{
379 Label: opt.Title,
380 Key: id,
381 })
382 }
383
384 sort.Slice(selectionOptions, func(i, j int) bool {
385 return selectionOptions[i].Label < selectionOptions[j].Label
386 })
387
388 return selectionOptions
389}
390
391func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
392 return DynamicSelectPreviewWithRefresh(options, addnewoption, nil)
393}
394
395func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addnewoption bool, refreshConfig *PreviewSelectionRefreshConfig) (SelectionOption, error) {
396 go preDownloadImages(options, 14)
397
398 // Removed boilerplate check
399
400 currentOptions := options
401
402 for {
403 var rofiInput strings.Builder
404 selectionOptions := previewOptionsToSortedSelection(currentOptions)
405
406 for _, opt := range selectionOptions {
407 cachePath, err := downloadToCache(currentOptions[opt.Key].CoverImage)
408 if err != nil {
409 Log(fmt.Sprintf("Error caching image: %v", err))
410 continue
411 }
412 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Label, cachePath))
413 }
414
415 if addnewoption {
416
417 rofiInput.WriteString("Add new anime\n")
418 }
419 rofiInput.WriteString("Back\n")
420 rofiInput.WriteString("Quit\n")
421
422 configPath := filepath.Join(GetStoragePath(), "selectanimepreview.rasi")
423 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
424 cmd.Stdin = strings.NewReader(rofiInput.String())
425 var stdout, stderr bytes.Buffer
426 cmd.Stdout = &stdout
427 cmd.Stderr = &stderr
428
429 if refreshConfig == nil || refreshConfig.Updates == nil {
430 if err := cmd.Run(); err != nil {
431 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
432 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
433 return SelectionOption{Key: "-2", Label: "Back"}, nil
434 }
435 return parsePreviewSelection(stdout.String(), selectionOptions)
436 }
437
438 if err := cmd.Start(); err != nil {
439 return SelectionOption{}, fmt.Errorf("failed to run Rofi preview menu: %w", err)
440 }
441
442 waitCh := make(chan error, 1)
443 go func() {
444 waitCh <- cmd.Wait()
445 }()
446
447 restartMenu := false
448
449 for !restartMenu {
450 select {
451 case err := <-waitCh:
452 if err != nil {
453 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
454 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
455 return SelectionOption{Key: "-2", Label: "Back"}, nil
456 }
457 return parsePreviewSelection(stdout.String(), selectionOptions)
458 case updatedList, ok := <-refreshConfig.Updates:
459 if !ok {
460 refreshConfig = nil
461 continue
462 }
463
464 updatedOptions := refreshConfig.BuildOptions(updatedList)
465 if reflect.DeepEqual(currentOptions, updatedOptions) {
466 continue
467 }
468
469 currentOptions = updatedOptions
470 restartMenu = true
471
472 if cmd.Process != nil {
473 _ = cmd.Process.Kill()
474 }
475 <-waitCh
476 }
477 }
478 }
479}
480
481func preDownloadImages(options map[string]RofiSelectPreview, count int) {
482 i := 0
483 for _, option := range options {
484 if i >= count {
485 break
486 }
487 downloadToCache(option.CoverImage)
488 i++
489 }
490}
491
492func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOption) (SelectionOption, error) {
493 selected := strings.TrimSpace(rawSelection)
494
495 switch selected {
496 case "":
497 return SelectionOption{Key: "-2", Label: "Back"}, nil
498 case "Add new anime":
499 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
500
501 case "Back":
502 return SelectionOption{Label: "Back", Key: "-2"}, nil
503 case "Quit":
504 return SelectionOption{Label: "Quit", Key: "-1"}, nil
505 }
506
507 for _, opt := range selectionOptions {
508 if opt.Label == selected {
509 return opt, nil
510 }
511 }
512
513 return SelectionOption{}, fmt.Errorf("selection not found in options")
514}
515
516func downloadToCache(imageURL string) (string, error) {
517 if strings.TrimSpace(imageURL) == "" {
518 return "", fmt.Errorf("image URL is empty")
519 }
520
521 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
522 if err := os.MkdirAll(cacheDir, 0755); err != nil {
523 return "", fmt.Errorf("failed to create cache directory: %w", err)
524 }
525
526 // Create a hash of the URL to use as filename
527 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
528 cachePath := filepath.Join(cacheDir, filename)
529
530 // Check if file already exists in cache
531 if info, err := os.Stat(cachePath); err == nil {
532 if info.Size() > 0 {
533 return cachePath, nil
534 }
535 _ = os.Remove(cachePath)
536 }
537
538 // Download the image
539 resp, err := sharedHTTPClient.Get(imageURL)
540 if err != nil {
541 return "", err
542 }
543 defer resp.Body.Close()
544 if resp.StatusCode != http.StatusOK {
545 return "", fmt.Errorf("failed to download image: status %d", resp.StatusCode)
546 }
547
548 file, err := os.Create(cachePath)
549 if err != nil {
550 return "", err
551 }
552
553 _, err = io.Copy(file, resp.Body)
554 if err != nil {
555 file.Close()
556 os.Remove(cachePath) // Clean up on error
557 return "", err
558 }
559 if err := file.Close(); err != nil {
560 os.Remove(cachePath)
561 return "", err
562 }
563
564 return cachePath, nil
565}
566
567func showCachedImagePreview(imageURL string) error {
568 cachePath, err := downloadToCache(imageURL)
569 if err != nil {
570 return err
571 }
572
573 // Display the image with ueberzugpp
574 cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
575 err = cmd.Start()
576 if err != nil {
577 return fmt.Errorf("failed to start image preview: %w", err)
578 }
579 time.Sleep(2 * time.Second) // Allow image to load for a moment
580 return nil
581}
582
583func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
584 return RofiSelectWithRefresh(options, isHomeMenu, nil)
585}
586
587func RofiSelectWithRefresh(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
588 currentOptions := options
589
590 for {
591 optionsString := buildRofiOptionsString(currentOptions, isHomeMenu)
592 configPath := filepath.Join(GetStoragePath(), "selectanime.rasi")
593 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
594 cmd.Stdin = strings.NewReader(optionsString)
595 var stdout, stderr bytes.Buffer
596 cmd.Stdout = &stdout
597 cmd.Stderr = &stderr
598
599 if refreshConfig == nil || refreshConfig.Updates == nil {
600 err := cmd.Run()
601 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
602 }
603
604 if err := cmd.Start(); err != nil {
605 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %w", err)
606 }
607
608 waitCh := make(chan error, 1)
609 go func() {
610 waitCh <- cmd.Wait()
611 }()
612
613 restartMenu := false
614
615 for !restartMenu {
616 select {
617 case err := <-waitCh:
618 if err != nil {
619 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
620 }
621 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
622 case updatedList, ok := <-refreshConfig.Updates:
623 if !ok {
624 refreshConfig = nil
625 continue
626 }
627
628 updatedOptions := refreshConfig.BuildOptions(updatedList)
629 if reflect.DeepEqual(currentOptions, updatedOptions) {
630 continue
631 }
632
633 currentOptions = updatedOptions
634 restartMenu = true
635
636 if cmd.Process != nil {
637 _ = cmd.Process.Kill()
638 }
639 <-waitCh
640 }
641 }
642 }
643}
644
645func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
646 return dynamicSelectInternal(options, nil)
647}
648
649// DynamicSelect displays a simple selection prompt without extra features
650func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
651 return dynamicSelectInternal(options, nil)
652}
653
654var promptSelect = DynamicSelect
655
656func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
657 return dynamicSelectInternal(options, refreshConfig)
658}
659
660func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
661 isHomeMenu := detectHomeMenu(options)
662
663 if isHomeMenu {
664 options = sortHomeMenuOptions(options)
665 }
666
667 if config := GetGlobalConfig(); config != nil && config.RofiSelection {
668 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
669 }
670
671 // Separate out the "add_new" sentinel so it is never sorted alphabetically.
672 // The addNewOption flag causes filterOptions() to append it after the sort.
673 hasAddNew := false
674 cleanOptions := make([]SelectionOption, 0, len(options))
675 for _, opt := range options {
676 if opt.Key == "add_new" {
677 hasAddNew = true
678 } else {
679 cleanOptions = append(cleanOptions, opt)
680 }
681 }
682
683 model := &Model{
684 allOptions: cleanOptions,
685 isHomeMenu: isHomeMenu,
686 addNewOption: hasAddNew,
687 }
688 model.filterOptions()
689
690 p := tea.NewProgram(model)
691 stopRefresh := make(chan struct{})
692
693 if refreshConfig != nil && refreshConfig.Updates != nil {
694 go func(lastOptions []SelectionOption) {
695 currentOptions := lastOptions
696 for {
697 select {
698 case <-stopRefresh:
699 return
700 case updatedList, ok := <-refreshConfig.Updates:
701 if !ok {
702 return
703 }
704
705 updatedOptions := refreshConfig.BuildOptions(updatedList)
706 if reflect.DeepEqual(currentOptions, updatedOptions) {
707 continue
708 }
709
710 currentOptions = updatedOptions
711 p.Send(optionsRefreshedMsg{options: updatedOptions})
712 }
713 }
714 }(append([]SelectionOption(nil), options...))
715 }
716
717 finalModel, err := p.Run()
718 close(stopRefresh)
719 if err != nil {
720 return SelectionOption{}, err
721 }
722
723 fmt.Print("\033[?25h")
724 fmt.Print("\033[?7h")
725
726 finalSelectionModel, ok := finalModel.(*Model)
727 if !ok {
728 return SelectionOption{}, fmt.Errorf("unexpected model type")
729 }
730
731 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
732 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
733 }
734 return SelectionOption{}, nil
735}
736
737func buildRofiOptionsString(options []SelectionOption, isHomeMenu bool) string {
738 optionsList := make([]string, 0, len(options)+2)
739 for _, opt := range options {
740 optionsList = append(optionsList, opt.Label)
741 }
742
743 if !isHomeMenu {
744 optionsList = append(optionsList, "Back")
745 }
746 optionsList = append(optionsList, "Quit")
747
748 return strings.Join(optionsList, "\n")
749}
750
751func parseRofiSelection(err error, rawSelection string, options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
752 if err != nil {
753 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
754 if isHomeMenu {
755 return SelectionOption{Key: "-1", Label: "Quit"}, nil
756 }
757 return SelectionOption{Key: "-2", Label: "Back"}, nil
758 }
759 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
760 }
761
762 selected := strings.TrimSpace(rawSelection)
763 switch selected {
764 case "":
765 if isHomeMenu {
766 return SelectionOption{Key: "-1", Label: "Quit"}, nil
767 }
768 return SelectionOption{Key: "-2", Label: "Back"}, nil
769 case "Back":
770 return SelectionOption{Label: "Back", Key: "-2"}, nil
771 case "Quit":
772 return SelectionOption{Label: "Quit", Key: "-1"}, nil
773 }
774
775 for _, opt := range options {
776 if opt.Label == selected {
777 return opt, nil
778 }
779 }
780
781 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
782}