internal/selection_menu.go
767 lines · 20341 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
288 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
289 }
290
291 // Back in its default position (after Add new anime) when filter doesn't target it
292 if !m.isHomeMenu && !backMatchesFilter {
293 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
294 }
295
296 // Quit is always last
297 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
298}
299
300func detectHomeMenu(options []SelectionOption) bool {
301 for _, opt := range options {
302 if opt.Key == "ALL" || opt.Key == "CURRENT" {
303 return true
304 }
305 }
306 return false
307}
308
309func findSelectionIndex(options []SelectionOption, previousKey string, previousLabel string, fallbackIndex int) int {
310 if previousKey != "" {
311 for idx, option := range options {
312 if option.Key == previousKey {
313 return idx
314 }
315 }
316 }
317
318 if previousLabel != "" {
319 for idx, option := range options {
320 if option.Label == previousLabel {
321 return idx
322 }
323 }
324 }
325
326 if fallbackIndex >= 0 && fallbackIndex < len(options) {
327 return fallbackIndex
328 }
329
330 if len(options) == 0 {
331 return -1
332 }
333
334 return min(fallbackIndex, len(options)-1)
335}
336
337func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
338 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
339 optMap := make(map[string]SelectionOption)
340 for _, opt := range options {
341 optMap[opt.Key] = opt
342 }
343
344 sorted := make([]SelectionOption, 0, len(options))
345 for _, key := range menuOrder {
346 if opt, exists := optMap[key]; exists {
347 sorted = append(sorted, opt)
348 delete(optMap, key)
349 }
350 }
351
352 for _, opt := range options {
353 if _, exists := optMap[opt.Key]; exists {
354 sorted = append(sorted, opt)
355 delete(optMap, opt.Key)
356 }
357 }
358
359 return sorted
360}
361
362func previewOptionsToSortedSelection(options map[string]RofiSelectPreview) []SelectionOption {
363 selectionOptions := make([]SelectionOption, 0, len(options))
364 for id, opt := range options {
365 selectionOptions = append(selectionOptions, SelectionOption{
366 Label: opt.Title,
367 Key: id,
368 })
369 }
370
371 sort.Slice(selectionOptions, func(i, j int) bool {
372 return selectionOptions[i].Label < selectionOptions[j].Label
373 })
374
375 return selectionOptions
376}
377
378func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
379 return DynamicSelectPreviewWithRefresh(options, addnewoption, nil)
380}
381
382func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addnewoption bool, refreshConfig *PreviewSelectionRefreshConfig) (SelectionOption, error) {
383 go preDownloadImages(options, 14)
384
385 userCurdConfig := GetGlobalConfig()
386 if userCurdConfig.StoragePath == "" {
387 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
388 }
389
390 currentOptions := options
391
392 for {
393 var rofiInput strings.Builder
394 selectionOptions := previewOptionsToSortedSelection(currentOptions)
395
396 for _, opt := range selectionOptions {
397 cachePath, err := downloadToCache(currentOptions[opt.Key].CoverImage)
398 if err != nil {
399 Log(fmt.Sprintf("Error caching image: %v", err))
400 continue
401 }
402 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Label, cachePath))
403 }
404
405 if addnewoption {
406
407 rofiInput.WriteString("Add new anime\n")
408 }
409 rofiInput.WriteString("Back\n")
410 rofiInput.WriteString("Quit\n")
411
412 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
413 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
414 cmd.Stdin = strings.NewReader(rofiInput.String())
415 var stdout, stderr bytes.Buffer
416 cmd.Stdout = &stdout
417 cmd.Stderr = &stderr
418
419 if refreshConfig == nil || refreshConfig.Updates == nil {
420 if err := cmd.Run(); err != nil {
421 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
422 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
423 return SelectionOption{Key: "-2", Label: "Back"}, nil
424 }
425 return parsePreviewSelection(stdout.String(), selectionOptions)
426 }
427
428 if err := cmd.Start(); err != nil {
429 return SelectionOption{}, fmt.Errorf("failed to run Rofi preview menu: %w", err)
430 }
431
432 waitCh := make(chan error, 1)
433 go func() {
434 waitCh <- cmd.Wait()
435 }()
436
437 restartMenu := false
438
439 for !restartMenu {
440 select {
441 case err := <-waitCh:
442 if err != nil {
443 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
444 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
445 return SelectionOption{Key: "-2", Label: "Back"}, nil
446 }
447 return parsePreviewSelection(stdout.String(), selectionOptions)
448 case updatedList, ok := <-refreshConfig.Updates:
449 if !ok {
450 refreshConfig = nil
451 continue
452 }
453
454 updatedOptions := refreshConfig.BuildOptions(updatedList)
455 if reflect.DeepEqual(currentOptions, updatedOptions) {
456 continue
457 }
458
459 currentOptions = updatedOptions
460 restartMenu = true
461
462 if cmd.Process != nil {
463 _ = cmd.Process.Kill()
464 }
465 <-waitCh
466 }
467 }
468 }
469}
470
471func preDownloadImages(options map[string]RofiSelectPreview, count int) {
472 i := 0
473 for _, option := range options {
474 if i >= count {
475 break
476 }
477 downloadToCache(option.CoverImage)
478 i++
479 }
480}
481
482func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOption) (SelectionOption, error) {
483 selected := strings.TrimSpace(rawSelection)
484
485 switch selected {
486 case "":
487 return SelectionOption{Key: "-2", Label: "Back"}, nil
488 case "Add new anime":
489 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
490
491 case "Back":
492 return SelectionOption{Label: "Back", Key: "-2"}, nil
493 case "Quit":
494 return SelectionOption{Label: "Quit", Key: "-1"}, nil
495 }
496
497 for _, opt := range selectionOptions {
498 if opt.Label == selected {
499 return opt, nil
500 }
501 }
502
503 return SelectionOption{}, fmt.Errorf("selection not found in options")
504}
505
506func downloadToCache(imageURL string) (string, error) {
507 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
508 if err := os.MkdirAll(cacheDir, 0755); err != nil {
509 return "", fmt.Errorf("failed to create cache directory: %w", err)
510 }
511
512 // Create a hash of the URL to use as filename
513 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
514 cachePath := filepath.Join(cacheDir, filename)
515
516 // Check if file already exists in cache
517 if _, err := os.Stat(cachePath); err == nil {
518 return cachePath, nil
519 }
520
521 // Download the image
522 resp, err := http.Get(imageURL)
523 if err != nil {
524 return "", err
525 }
526 defer resp.Body.Close()
527
528 file, err := os.Create(cachePath)
529 if err != nil {
530 return "", err
531 }
532 defer file.Close()
533
534 _, err = io.Copy(file, resp.Body)
535 if err != nil {
536 os.Remove(cachePath) // Clean up on error
537 return "", err
538 }
539
540 return cachePath, nil
541}
542
543func showCachedImagePreview(imageURL string) error {
544 cachePath, err := downloadToCache(imageURL)
545 if err != nil {
546 return err
547 }
548
549 // Display the image with ueberzugpp
550 cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
551 err = cmd.Start()
552 if err != nil {
553 return fmt.Errorf("failed to start image preview: %w", err)
554 }
555 time.Sleep(2 * time.Second) // Allow image to load for a moment
556 return nil
557}
558
559func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
560 return RofiSelectWithRefresh(options, isHomeMenu, nil)
561}
562
563func RofiSelectWithRefresh(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
564 userCurdConfig := GetGlobalConfig()
565 if userCurdConfig.StoragePath == "" {
566 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
567 }
568
569 currentOptions := options
570
571 for {
572 optionsString := buildRofiOptionsString(currentOptions, isHomeMenu)
573 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
574 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
575 cmd.Stdin = strings.NewReader(optionsString)
576 var stdout, stderr bytes.Buffer
577 cmd.Stdout = &stdout
578 cmd.Stderr = &stderr
579
580 if refreshConfig == nil || refreshConfig.Updates == nil {
581 err := cmd.Run()
582 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
583 }
584
585 if err := cmd.Start(); err != nil {
586 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %w", err)
587 }
588
589 waitCh := make(chan error, 1)
590 go func() {
591 waitCh <- cmd.Wait()
592 }()
593
594 restartMenu := false
595
596 for !restartMenu {
597 select {
598 case err := <-waitCh:
599 if err != nil {
600 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
601 }
602 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
603 case updatedList, ok := <-refreshConfig.Updates:
604 if !ok {
605 refreshConfig = nil
606 continue
607 }
608
609 updatedOptions := refreshConfig.BuildOptions(updatedList)
610 if reflect.DeepEqual(currentOptions, updatedOptions) {
611 continue
612 }
613
614 currentOptions = updatedOptions
615 restartMenu = true
616
617 if cmd.Process != nil {
618 _ = cmd.Process.Kill()
619 }
620 <-waitCh
621 }
622 }
623 }
624}
625
626func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
627 return dynamicSelectInternal(options, nil)
628}
629
630// DynamicSelect displays a simple selection prompt without extra features
631func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
632 return dynamicSelectInternal(options, nil)
633}
634
635func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
636 return dynamicSelectInternal(options, refreshConfig)
637}
638
639func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
640 isHomeMenu := detectHomeMenu(options)
641
642 if isHomeMenu {
643 options = sortHomeMenuOptions(options)
644 }
645
646 for _, opt := range options {
647 if strings.Contains(opt.Label, "Bleach (366 episodes) [animepahe]") {
648 return opt, nil
649 }
650 }
651
652 if GetGlobalConfig().RofiSelection {
653 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
654 }
655
656 // Separate out the "add_new" sentinel so it is never sorted alphabetically.
657 // The addNewOption flag causes filterOptions() to append it after the sort.
658 hasAddNew := false
659 cleanOptions := make([]SelectionOption, 0, len(options))
660 for _, opt := range options {
661 if opt.Key == "add_new" {
662 hasAddNew = true
663 } else {
664 cleanOptions = append(cleanOptions, opt)
665 }
666 }
667
668 model := &Model{
669 allOptions: cleanOptions,
670 isHomeMenu: isHomeMenu,
671 addNewOption: hasAddNew,
672 }
673 model.filterOptions()
674
675 p := tea.NewProgram(model)
676 stopRefresh := make(chan struct{})
677
678 if refreshConfig != nil && refreshConfig.Updates != nil {
679 go func(lastOptions []SelectionOption) {
680 currentOptions := lastOptions
681 for {
682 select {
683 case <-stopRefresh:
684 return
685 case updatedList, ok := <-refreshConfig.Updates:
686 if !ok {
687 return
688 }
689
690 updatedOptions := refreshConfig.BuildOptions(updatedList)
691 if reflect.DeepEqual(currentOptions, updatedOptions) {
692 continue
693 }
694
695 currentOptions = updatedOptions
696 p.Send(optionsRefreshedMsg{options: updatedOptions})
697 }
698 }
699 }(append([]SelectionOption(nil), options...))
700 }
701
702 finalModel, err := p.Run()
703 close(stopRefresh)
704 if err != nil {
705 return SelectionOption{}, err
706 }
707
708 fmt.Print("\033[?25h")
709 fmt.Print("\033[?7h")
710
711 finalSelectionModel, ok := finalModel.(*Model)
712 if !ok {
713 return SelectionOption{}, fmt.Errorf("unexpected model type")
714 }
715
716 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
717 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
718 }
719 return SelectionOption{}, nil
720}
721
722func buildRofiOptionsString(options []SelectionOption, isHomeMenu bool) string {
723 optionsList := make([]string, 0, len(options)+2)
724 for _, opt := range options {
725 optionsList = append(optionsList, opt.Label)
726 }
727
728 if !isHomeMenu {
729 optionsList = append(optionsList, "Back")
730 }
731 optionsList = append(optionsList, "Quit")
732
733 return strings.Join(optionsList, "\n")
734}
735
736func parseRofiSelection(err error, rawSelection string, options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
737 if err != nil {
738 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
739 if isHomeMenu {
740 return SelectionOption{Key: "-1", Label: "Quit"}, nil
741 }
742 return SelectionOption{Key: "-2", Label: "Back"}, nil
743 }
744 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
745 }
746
747 selected := strings.TrimSpace(rawSelection)
748 switch selected {
749 case "":
750 if isHomeMenu {
751 return SelectionOption{Key: "-1", Label: "Quit"}, nil
752 }
753 return SelectionOption{Key: "-2", Label: "Back"}, nil
754 case "Back":
755 return SelectionOption{Label: "Back", Key: "-2"}, nil
756 case "Quit":
757 return SelectionOption{Label: "Quit", Key: "-1"}, nil
758 }
759
760 for _, opt := range options {
761 if opt.Label == selected {
762 return opt, nil
763 }
764 }
765
766 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
767}