internal/selection_menu.go
165 lines · 4271 bytes
1package internal
2
3import (
4 "fmt"
5 "strings"
6 tea "github.com/charmbracelet/bubbletea"
7)
8
9// SelectionOption holds the label and the internal key
10type SelectionOption struct {
11 Label string
12 Key string
13}
14
15// Model represents the application state for the selection prompt
16type 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
22}
23
24// Init initializes the model
25func (m Model) Init() tea.Cmd {
26 return nil
27}
28
29// Update handles user input and updates the model
30func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
31 // Handle terminal resize messages
32 if wsm, ok := msg.(tea.WindowSizeMsg); ok {
33 m.terminalHeight = wsm.Height // Get the terminal height
34 }
35
36 // Only filter options if a key press modifies the filter
37 updateFilter := false
38
39 switch msg := msg.(type) {
40 case tea.KeyMsg:
41 switch msg.String() {
42 case "ctrl+c", "q":
43 return m, tea.Quit
44 case "backspace":
45 if len(m.filter) > 0 {
46 m.filter = m.filter[:len(m.filter)-1]
47 updateFilter = true // Mark for updating the filter
48 }
49 case "down":
50 // Move cursor down within bounds
51 if m.selected < len(m.filteredKeys)-1 {
52 m.selected++
53 }
54 case "up":
55 // Move cursor up within bounds
56 if m.selected > 0 {
57 m.selected--
58 }
59 case "enter":
60 return m, tea.Quit // Or return the selected option
61 default:
62 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
63 m.filter += msg.String()
64 updateFilter = true // Mark for updating the filter
65 }
66 }
67 }
68
69 // Only filter options if the filter was actually modified
70 if updateFilter {
71 m.filterOptions()
72 // Reset selected index after filtering
73 m.selected = 0
74 }
75
76 return m, nil
77}
78
79// View renders the UI
80func (m Model) View() string {
81 var b strings.Builder
82
83 b.WriteString("Search (Press Ctrl+C to quit):\n\n")
84 b.WriteString("Filter: " + m.filter + "\n\n")
85
86 if len(m.filteredKeys) == 0 {
87 b.WriteString("No matches found.\n")
88 } else {
89 // Determine how many entries can fit in the terminal
90 maxEntries := m.terminalHeight - 4 // Adjust for header and padding
91 if maxEntries < 1 {
92 maxEntries = 1 // At least show one option
93 }
94
95 // Limit the number of displayed entries
96 start := m.selected
97 if start >= len(m.filteredKeys) {
98 start = len(m.filteredKeys) - 1
99 }
100 end := start + maxEntries
101 if end > len(m.filteredKeys) {
102 end = len(m.filteredKeys)
103 }
104 if start > end {
105 start = end
106 }
107
108 // Display the filtered keys with selection indicator
109 for i := start; i < end; i++ {
110 if i == m.selected {
111 b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label))
112 } else {
113 b.WriteString(fmt.Sprintf(" %s\n", m.filteredKeys[i].Label))
114 }
115 }
116 }
117
118 return b.String()
119}
120
121// filterOptions filters options based on the search term
122func (m *Model) filterOptions() {
123 // Clear the filteredKeys slice before appending new matches
124 m.filteredKeys = []SelectionOption{}
125
126 for key, value := range m.options {
127 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
128 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
129 }
130 }
131}
132
133// DynamicSelect displays a full-screen selection prompt with search
134func DynamicSelect(options map[string]string) (SelectionOption, error) {
135 // ClearScreen()
136 // defer RestoreScreen()
137 model := &Model{ // Use a pointer to Model
138 options: options,
139 filteredKeys: make([]SelectionOption, 0), // Initialize filteredKeys
140 }
141
142 // Populate filteredKeys initially
143 model.filterOptions()
144
145 // Create a new Program instance
146 p := tea.NewProgram(model)
147
148 // Run the program and capture the final model and any error
149 finalModel, err := p.Run()
150 if err != nil {
151 return SelectionOption{}, err
152 }
153
154 // Type assert to get the specific model type
155 finalSelectionModel, ok := finalModel.(*Model)
156 if !ok {
157 return SelectionOption{}, fmt.Errorf("unexpected model type")
158 }
159
160 // Return the selected option after quitting
161 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
162 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
163 }
164 return SelectionOption{}, nil
165}