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
22
33import (
44 "fmt"
5 "sort"
56 "strings"
7
68 tea "github.com/charmbracelet/bubbletea"
79)
810
@@ -14,11 +16,13 @@ type SelectionOption struct {
1416
1517// Model represents the application state for the selection prompt
1618type Model struct {
17 options map[string]string // Now using a map for options
18 filter string
19 filteredKeys []SelectionOption
20 selected int
21 terminalHeight int // New field to hold the terminal height
19 options map[string]string
20 filter string
21 filteredKeys []SelectionOption
22 selected int
23 terminalWidth int
24 terminalHeight int
25 scrollOffset int // Track the topmost visible item
2226}
2327
2428// Init initializes the model
@@ -30,10 +34,10 @@ func (m Model) Init() tea.Cmd {
3034func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
3135 // Handle terminal resize messages
3236 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
3439 }
3540
36 // Only filter options if a key press modifies the filter
3741 updateFilter := false
3842
3943 switch msg := msg.(type) {
@@ -44,136 +48,139 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
4448 case "backspace":
4549 if len(m.filter) > 0 {
4650 m.filter = m.filter[:len(m.filter)-1]
47 updateFilter = true // Mark for updating the filter
51 updateFilter = true
4852 }
4953 case "down":
50 // Move cursor down within bounds
54 // Move the selection cursor down
5155 if m.selected < len(m.filteredKeys)-1 {
5256 m.selected++
5357 }
58
59 // Scroll the view if necessary
60 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
61 m.scrollOffset++
62 }
5463 case "up":
55 // Move cursor up within bounds
64 // Move the selection cursor up
5665 if m.selected > 0 {
5766 m.selected--
5867 }
68
69 // Scroll the view if necessary
70 if m.selected < m.scrollOffset {
71 m.scrollOffset--
72 }
5973 case "enter":
60 // If "Add new anime" is selected, handle it here
61 if m.filteredKeys[m.selected].Key == "add_new" {
62 // Implement your logic for adding a new anime
63 fmt.Println("Adding a new anime...") // Temporary print statement
64 return m, tea.Quit
65 }
66 return m, tea.Quit // Or return the selected option for other cases
67 default:
74 if m.filteredKeys[m.selected].Key == "add_new" {
75 fmt.Println("Adding a new anime...")
76 return m, tea.Quit
77 }
78 return m, tea.Quit
79 default:
6880 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
6981 m.filter += msg.String()
70 updateFilter = true // Mark for updating the filter
82 updateFilter = true
7183 }
7284 }
7385 }
7486
75 // Only filter options if the filter was actually modified
7687 if updateFilter {
7788 m.filterOptions()
78 // Reset selected index after filtering
79 m.selected = 0
89 m.selected = 0 // Reset selection to the first item after filtering
90 m.scrollOffset = 0 // Reset scrolling
8091 }
8192
8293 return m, nil
8394}
8495
85// View renders the UI
96// View renders the UI and only shows as many options as fit in the terminal
8697func (m Model) View() string {
87 var b strings.Builder
88
89 b.WriteString("Search (Press Ctrl+C to quit):\n\n")
90 b.WriteString("Filter: " + m.filter + "\n\n")
91
92 if len(m.filteredKeys) == 0 {
93 b.WriteString("No matches found.\n")
94 } else {
95 // Determine how many entries can fit in the terminal
96 maxEntries := m.terminalHeight - 4 // Adjust for header and padding
97 if maxEntries < 1 {
98 maxEntries = 1 // At least show one option
99 }
100
101 // Limit the number of displayed entries
102 start := m.selected
103 if start >= len(m.filteredKeys) {
104 start = len(m.filteredKeys) - 1
105 }
106 end := start + maxEntries
107 if end > len(m.filteredKeys) {
108 end = len(m.filteredKeys)
109 }
110 if start > end {
111 start = end
112 }
113
114 // Display the filtered keys with selection indicator
115 for i := start; i < end; i++ {
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()
98 var b strings.Builder
99
100 // Display the search prompt and filter
101 b.WriteString("Search (Press Ctrl+C to quit):\n")
102 b.WriteString("Filter: " + m.filter + "\n")
103
104 if len(m.filteredKeys) == 0 {
105 b.WriteString("\nNo matches found.\n")
106 } else {
107 visibleItems := m.visibleItemsCount()
108
109 // Determine the slice of items to display based on scroll offset
110 start := m.scrollOffset
111 end := start + visibleItems
112 if end > len(m.filteredKeys) {
113 end = len(m.filteredKeys)
114 }
115
116 // Render the options within the visible range
117 for i := start; i < end; i++ {
118 if i == m.selected {
119 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
120 } else {
121 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label)) // Regular option
122 }
123 }
124 }
125
126 return b.String()
125127}
126128
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}
127134
128// filterOptions filters options based on the search term
135// filterOptions filters and sorts options based on the search term
129136func (m *Model) filterOptions() {
130 // Clear the filteredKeys slice before appending new matches
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}
137 m.filteredKeys = []SelectionOption{}
147138
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 }
148149
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
150165func DynamicSelect(options map[string]string) (SelectionOption, error) {
151 // ClearScreen()
152 // defer RestoreScreen()
153 model := &Model{ // Use a pointer to Model
154 options: options,
155 filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
166 model := &Model{
167 options: options,
168 filteredKeys: make([]SelectionOption, 0),
156169 }
157170
158 // Populate filteredKeys initially
159171 model.filterOptions()
160
161 // Create a new Program instance
162172 p := tea.NewProgram(model)
163173
164 // Run the program and capture the final model and any error
165174 finalModel, err := p.Run()
166175 if err != nil {
167176 return SelectionOption{}, err
168177 }
169178
170 // Type assert to get the specific model type
171179 finalSelectionModel, ok := finalModel.(*Model)
172180 if !ok {
173181 return SelectionOption{}, fmt.Errorf("unexpected model type")
174182 }
175183
176 // Return the selected option after quitting
177184 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
178185 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
179186 }