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