-
Notifications
You must be signed in to change notification settings - Fork 0
/
input_bar.go
247 lines (212 loc) · 5.63 KB
/
input_bar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package component
import (
"regexp"
"strings"
"sync"
"github.com/gdamore/tcell/v2"
"github.com/kopecmaciej/mongui/config"
"github.com/kopecmaciej/mongui/mongo"
"github.com/kopecmaciej/tview"
"github.com/rs/zerolog/log"
)
const (
InputBarComponent = "InputBar"
)
type InputBar struct {
*Component
*tview.InputField
historyModal *HistoryModal
style *config.InputBarStyle
mutex sync.Mutex
enabled bool
autocompleteOn bool
docKeys []string
defaultText string
}
func NewInputBar(label string) *InputBar {
i := &InputBar{
Component: NewComponent(InputBarComponent),
InputField: tview.NewInputField().
SetLabel(" " + label + ": "),
enabled: false,
autocompleteOn: false,
}
i.SetAfterInitFunc(i.init)
return i
}
func (i *InputBar) init() error {
i.setStyle()
i.setKeybindings()
i.Subscribe()
go i.handleEvents()
return nil
}
func (i *InputBar) setStyle() {
i.style = &i.app.Styles.InputBar
i.SetBorder(true)
i.SetFieldTextColor(i.style.InputColor.Color())
// Autocomplete styles
a := i.style.Autocomplete
background := a.BackgroundColor.Color()
main := tcell.StyleDefault.
Background(a.BackgroundColor.Color()).
Foreground(a.TextColor.Color())
selected := tcell.StyleDefault.
Background(a.ActiveBackgroundColor.Color()).
Foreground(a.ActiveTextColor.Color())
second := tcell.StyleDefault.
Background(a.BackgroundColor.Color()).
Foreground(a.SecondaryTextColor.Color()).
Italic(true)
i.SetAutocompleteStyles(background, main, selected, second, true)
}
func (i *InputBar) setKeybindings() {
i.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Rune() {
case '{':
if i.GetWordAtCursor() == "" {
i.SetWordAtCursor("{ <$0> }")
return nil
}
case '[':
if i.GetWordAtCursor() == "" {
i.SetWordAtCursor("[ <$0> ]")
return nil
}
}
k := i.app.Keys
switch {
case k.Contains(k.Root.Content.QueryBar.ShowHistory, event.Name()):
if i.historyModal != nil {
i.displayHistoryModal()
}
case k.Contains(k.Root.Content.QueryBar.ClearInput, event.Name()):
i.SetText("")
i.SetWordAtCursor(i.defaultText)
}
return event
})
}
// SetDefaultText sets default text for the input bar
func (i *InputBar) SetDefaultText(text string) {
i.defaultText = text
}
// DoneFuncHandler sets DoneFunc for the input bar
// It accepts two functions: accept and reject which are called
// when user accepts or rejects the input
func (i *InputBar) DoneFuncHandler(accept func(string), reject func()) {
i.SetDoneFunc(func(key tcell.Key) {
switch key {
case tcell.KeyEsc:
i.Toggle()
reject()
case tcell.KeyEnter:
i.Toggle()
text := i.GetText()
if i.historyModal != nil {
err := i.historyModal.SaveToHistory(text)
if err != nil {
log.Error().Err(err).Msg("Error saving query to history")
}
}
accept(text)
}
})
}
// EnableHistory enables history modal
func (i *InputBar) EnableHistory() {
i.historyModal = NewHistoryModal()
if err := i.historyModal.Init(i.app); err != nil {
log.Error().Err(err).Msg("Error initializing history modal")
}
}
// EnableAutocomplete enables autocomplete
func (i *InputBar) EnableAutocomplete() {
ma := mongo.NewMongoAutocomplete()
mongoKeywords := ma.Operators
i.SetAutocompleteFunc(func(currentText string) (entries []tview.AutocompleteItem) {
if strings.HasPrefix(currentText, "\"") {
currentText = currentText[1:]
}
words := strings.Fields(currentText)
if len(words) > 0 {
currentWord := i.GetWordAtCursor()
// if word starts with { or [ then we are inside object or array
// and we should ommmit this character
if strings.HasPrefix(currentWord, "{") || strings.HasPrefix(currentWord, "[") {
currentWord = currentWord[1:]
}
if currentWord == "" {
return nil
}
// support for mongo keywords
for _, keyword := range mongoKeywords {
escaped := regexp.QuoteMeta(currentWord)
if matched, _ := regexp.MatchString("(?i)^"+escaped, keyword.Display); matched {
entry := tview.AutocompleteItem{Main: keyword.Display, Secondary: keyword.Description}
entries = append(entries, entry)
}
}
// support for document keys
if i.docKeys != nil {
for _, keyword := range i.docKeys {
if matched, _ := regexp.MatchString("(?i)^"+currentWord, keyword); matched {
entries = append(entries, tview.AutocompleteItem{Main: keyword})
}
}
}
}
return entries
})
i.SetAutocompletedFunc(func(text string, index, source int) bool {
if source == 0 {
return false
}
key := ma.GetOperatorByDisplay(text)
if key != nil {
text = key.InsertText
}
i.SetWordAtCursor(text)
return true
})
}
// LoadNewKeys loads new keys for autocomplete
// It is used when switching databases or collections
func (i *InputBar) LoadNewKeys(keys []string) {
i.docKeys = keys
}
// Display HistoryModal on the screen
func (i *InputBar) displayHistoryModal() {
err := i.historyModal.Render()
if err != nil {
ShowErrorModal(i.app.Root, "Error rendering history modal", err)
}
}
// Draws default text if input is empty
func (i *InputBar) Toggle() {
i.Component.Toggle()
if i.GetText() == "" {
go i.app.QueueUpdateDraw(func() {
i.SetWordAtCursor(i.defaultText)
})
}
}
func (i *InputBar) handleEvents() {
for event := range i.listener {
sender, eventKey := event.Sender, event.EventKey
switch sender {
case i.historyModal.GetIdentifier():
switch eventKey.Key() {
case tcell.KeyEnter:
i.app.QueueUpdateDraw(func() {
i.SetText(i.historyModal.GetText())
i.app.SetFocus(i)
})
case tcell.KeyEsc, tcell.KeyCtrlY:
i.app.QueueUpdateDraw(func() {
i.app.SetFocus(i)
})
}
}
}
}