Commit 49955f9fc2

49955f9fc2f48f64d43e473d7fc5ae7a3a7e3882

parent: 8413dd9004

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-22 10:58 UTC

Fix: Better selection process

Layout: unified · split

internal/selection_menu.go +98 −91
@@ -2,7 +2,9 @@ package internal
2 2
3import ( 3import (
4 "fmt" 4 "fmt"
5 "sort"
5 "strings" 6 "strings"
7
6 tea "github.com/charmbracelet/bubbletea" 8 tea "github.com/charmbracelet/bubbletea"
7) 9)
8 10
@@ -14,11 +16,13 @@ type SelectionOption struct {
14 16
15// Model represents the application state for the selection prompt 17// Model represents the application state for the selection prompt
16type Model struct { 18type Model struct {
17 options map[string]string // Now using a map for options 19 options map[string]string
18 filter string 20 filter string
19 filteredKeys []SelectionOption 21 filteredKeys []SelectionOption
20 selected int 22 selected int
21 terminalHeight int // New field to hold the terminal height 23 terminalWidth int
24 terminalHeight int
25 scrollOffset int // Track the topmost visible item
22} 26}
23 27
24// Init initializes the model 28// Init initializes the model
@@ -30,10 +34,10 @@ func (m Model) Init() tea.Cmd {
30func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { 34func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
31 // Handle terminal resize messages 35 // Handle terminal resize messages
32 if wsm, ok := msg.(tea.WindowSizeMsg); ok { 36 if wsm, ok := msg.(tea.WindowSizeMsg); ok {
33 m.terminalHeight = wsm.Height // Get the terminal height 37 m.terminalWidth = wsm.Width
38 m.terminalHeight = wsm.Height
34 } 39 }
35 40
36 // Only filter options if a key press modifies the filter
37 updateFilter := false 41 updateFilter := false
38 42
39 switch msg := msg.(type) { 43 switch msg := msg.(type) {
@@ -44,136 +48,139 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
44 case "backspace": 48 case "backspace":
45 if len(m.filter) > 0 { 49 if len(m.filter) > 0 {
46 m.filter = m.filter[:len(m.filter)-1] 50 m.filter = m.filter[:len(m.filter)-1]
47 updateFilter = true // Mark for updating the filter 51 updateFilter = true
48 } 52 }
49 case "down": 53 case "down":
50 // Move cursor down within bounds 54 // Move the selection cursor down
51 if m.selected < len(m.filteredKeys)-1 { 55 if m.selected < len(m.filteredKeys)-1 {
52 m.selected++ 56 m.selected++
53 } 57 }
58
59 // Scroll the view if necessary
60 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
61 m.scrollOffset++
62 }
54 case "up": 63 case "up":
55 // Move cursor up within bounds 64 // Move the selection cursor up
56 if m.selected > 0 { 65 if m.selected > 0 {
57 m.selected-- 66 m.selected--
58 } 67 }
68
69 // Scroll the view if necessary
70 if m.selected < m.scrollOffset {
71 m.scrollOffset--
72 }
59 case "enter": 73 case "enter":
60 // If "Add new anime" is selected, handle it here 74 if m.filteredKeys[m.selected].Key == "add_new" {
61 if m.filteredKeys[m.selected].Key == "add_new" { 75 fmt.Println("Adding a new anime...")
62 // Implement your logic for adding a new anime 76 return m, tea.Quit
63 fmt.Println("Adding a new anime...") // Temporary print statement 77 }
64 return m, tea.Quit 78 return m, tea.Quit
65 } 79 default:
66 return m, tea.Quit // Or return the selected option for other cases
67 default:
68 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" { 80 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
69 m.filter += msg.String() 81 m.filter += msg.String()
70 updateFilter = true // Mark for updating the filter 82 updateFilter = true
71 } 83 }
72 } 84 }
73 } 85 }
74 86
75 // Only filter options if the filter was actually modified
76 if updateFilter { 87 if updateFilter {
77 m.filterOptions() 88 m.filterOptions()
78 // Reset selected index after filtering 89 m.selected = 0 // Reset selection to the first item after filtering
79 m.selected = 0 90 m.scrollOffset = 0 // Reset scrolling
80 } 91 }
81 92
82 return m, nil 93 return m, nil
83} 94}
84 95
85// View renders the UI 96// View renders the UI and only shows as many options as fit in the terminal
86func (m Model) View() string { 97func (m Model) View() string {
87 var b strings.Builder 98 var b strings.Builder
88 99
89 b.WriteString("Search (Press Ctrl+C to quit):\n\n") 100 // Display the search prompt and filter
90 b.WriteString("Filter: " + m.filter + "\n\n") 101 b.WriteString("Search (Press Ctrl+C to quit):\n")
91 102 b.WriteString("Filter: " + m.filter + "\n")
92 if len(m.filteredKeys) == 0 { 103
93 b.WriteString("No matches found.\n") 104 if len(m.filteredKeys) == 0 {
94 } else { 105 b.WriteString("\nNo matches found.\n")
95 // Determine how many entries can fit in the terminal 106 } else {
96 maxEntries := m.terminalHeight - 4 // Adjust for header and padding 107 visibleItems := m.visibleItemsCount()
97 if maxEntries < 1 { 108
98 maxEntries = 1 // At least show one option 109 // Determine the slice of items to display based on scroll offset
99 } 110 start := m.scrollOffset
100 111 end := start + visibleItems
101 // Limit the number of displayed entries 112 if end > len(m.filteredKeys) {
102 start := m.selected 113 end = len(m.filteredKeys)
103 if start >= len(m.filteredKeys) { 114 }
104 start = len(m.filteredKeys) - 1 115
105 } 116 // Render the options within the visible range
106 end := start + maxEntries 117 for i := start; i < end; i++ {
107 if end > len(m.filteredKeys) { 118 if i == m.selected {
108 end = len(m.filteredKeys) 119 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
109 } 120 } else {
110 if start > end { 121 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label)) // Regular option
111 start = end 122 }
112 } 123 }
113 124 }
114 // Display the filtered keys with selection indicator 125
115 for i := start; i < end; i++ { 126 return b.String()
116 if i == m.selected {
117 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label))
118 } else {
119 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label))
120 }
121 }
122 }
123
124 return b.String()
125} 127}
126 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}
127 134
128// filterOptions filters options based on the search term 135// filterOptions filters and sorts options based on the search term
129func (m *Model) filterOptions() { 136func (m *Model) filterOptions() {
130 // Clear the filteredKeys slice before appending new matches 137 m.filteredKeys = []SelectionOption{}
131 m.filteredKeys = []SelectionOption{}
132
133 for key, value := range m.options {
134 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
135 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
136 }
137 }
138
139 // If no matches were found, add the "Add new anime" option
140 if len(m.filteredKeys) == 0 {
141 m.filteredKeys = append(m.filteredKeys, SelectionOption{
142 Label: "Add new anime",
143 Key: "add_new", // Special key to identify this option
144 })
145 }
146}
147 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 }
148 149
149// DynamicSelect displays a full-screen selection prompt with search 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
150func DynamicSelect(options map[string]string) (SelectionOption, error) { 165func DynamicSelect(options map[string]string) (SelectionOption, error) {
151 // ClearScreen() 166 model := &Model{
152 // defer RestoreScreen() 167 options: options,
153 model := &Model{ // Use a pointer to Model 168 filteredKeys: make([]SelectionOption, 0),
154 options: options,
155 filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
156 } 169 }
157 170
158 // Populate filteredKeys initially
159 model.filterOptions() 171 model.filterOptions()
160
161 // Create a new Program instance
162 p := tea.NewProgram(model) 172 p := tea.NewProgram(model)
163 173
164 // Run the program and capture the final model and any error
165 finalModel, err := p.Run() 174 finalModel, err := p.Run()
166 if err != nil { 175 if err != nil {
167 return SelectionOption{}, err 176 return SelectionOption{}, err
168 } 177 }
169 178
170 // Type assert to get the specific model type
171 finalSelectionModel, ok := finalModel.(*Model) 179 finalSelectionModel, ok := finalModel.(*Model)
172 if !ok { 180 if !ok {
173 return SelectionOption{}, fmt.Errorf("unexpected model type") 181 return SelectionOption{}, fmt.Errorf("unexpected model type")
174 } 182 }
175 183
176 // Return the selected option after quitting
177 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) { 184 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
178 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil 185 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
179 } 186 }