-
Notifications
You must be signed in to change notification settings - Fork 0
/
complex_select.go
486 lines (444 loc) · 11.7 KB
/
complex_select.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package cli
import (
"fmt"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/gizak/termui"
py "github.com/qjpcpu/common.v2/pinyin"
)
type selectListMode int
const (
ModeNorm selectListMode = iota
ModeSearch
)
type ComplexSelect struct {
// all items user can select from
items []string
// hints
hints []string
// selected item index
selectedIndex int
// whether nothing selected
selectNothing bool
// max lines display in single screen
maxLine int
// original title
title string
// term writer, parse term input
termWriter *TermWriter
uilist *termui.List
mode selectListMode
search *SearchObj
}
func NewComplexSelect(initialIndex int, items []string) *ComplexSelect {
// term writer for fast select by number
termWriter := NewTermWriter()
termWriter.AddTerm("0gg", ``, "gg")
termWriter.AddTerm("gg", `\d+`, "gg")
termWriter.AddTerm("G", ``, "G")
ls := &ComplexSelect{
selectedIndex: initialIndex,
items: items,
hints: make([]string, len(items)),
selectNothing: false,
maxLine: 20,
mode: ModeNorm,
termWriter: termWriter,
search: &SearchObj{
SearchTitle: "Search: ",
},
title: "Help:(1: <Enter>Confirm 2: </|C-s>Search 3: <ESC|q|C-c>Exit)",
}
ls.search.getOriginalSelectedIndex = func() int {
return ls.selectedIndex
}
return ls
}
func NewComplexSelectWithHints(initialIndex int, items, hints []string) *ComplexSelect {
list := NewComplexSelect(initialIndex, items)
for i := range items {
list.hints[i] = hints[i]
}
return list
}
// IsSelectNothing true: exit with nothing selected
func (sl *ComplexSelect) IsSelectNothing() bool {
return sl.selectNothing
}
// Selected return selected index
func (sl *ComplexSelect) Selected() int {
return sl.selectedIndex
}
// InSearchMode is in search mode
func (sl *ComplexSelect) InSearchMode() bool {
return sl.mode == ModeSearch
}
func (sl *ComplexSelect) InNormMode() bool {
return sl.mode == ModeNorm
}
// private methods
// move cursor by offset and repaint
func (sl *ComplexSelect) repaint(offset int) {
nIndex := offset + sl.selectedIndex
size := len(sl.items)
if nIndex < 0 {
nIndex += (1 - nIndex/size) * size
}
sl.selectedIndex = nIndex % len(sl.items)
sl.uilist.Items = sl.formatCommands()
termui.Render(termui.Body)
}
func (slist *ComplexSelect) createUI() {
ls := termui.NewList()
ls.Items = slist.formatCommands()
ls.ItemFgColor = termui.ColorCyan
ls.BorderLabel = slist.title
ls.Height = termui.TermHeight()
termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, ls)))
slist.uilist = ls
termui.Body.Align()
termui.Render(termui.Body)
}
func (sl *ComplexSelect) doSearch() {
sl.search.SearchResultsIndices = []int{}
sl.search.SelectedResultIndex = 0
for i, c := range sl.items {
if _, idx := py.FuzzyContain(strings.ToLower(c), strings.ToLower(sl.search.QueryStr)); idx >= 0 {
sl.search.SearchResultsIndices = append(sl.search.SearchResultsIndices, i)
}
}
sl.uilist.BorderLabel = sl.search.Title()
sl.repaint(sl.search.Current())
}
func (sl *ComplexSelect) appendQuery(qs string) {
sl.search.QueryStr += qs
sl.doSearch()
}
func (sl *ComplexSelect) reset() {
sl.mode = ModeNorm
sl.resetSearch()
sl.uilist.BorderLabel = sl.title
}
func (slist *ComplexSelect) handleKeyboardEvents() {
moveNext := func(termui.Event) {
if slist.InSearchMode() {
offset := slist.search.Next()
slist.uilist.BorderLabel = slist.search.Title()
slist.repaint(offset)
} else {
slist.repaint(1)
}
}
movePrev := func(termui.Event) {
if slist.InSearchMode() {
offset := slist.search.Prev()
slist.uilist.BorderLabel = slist.search.Title()
slist.repaint(offset)
} else {
slist.repaint(-1)
}
}
pageDown := func(termui.Event) {
if !slist.InSearchMode() {
slist.repaint(10)
}
}
pageUp := func(termui.Event) {
if !slist.InSearchMode() {
slist.repaint(-10)
}
}
termui.Handle("/sys/kbd/<enter>", func(termui.Event) {
termui.StopLoop()
})
termui.Handle("/sys/kbd/<escape>", func(termui.Event) {
if slist.InSearchMode() {
slist.reset()
slist.repaint(0)
} else {
termui.StopLoop()
slist.selectNothing = true
}
})
termui.Handle("/sys/kbd/q", func(termui.Event) {
if slist.InNormMode() {
termui.StopLoop()
slist.selectNothing = true
} else {
slist.appendQuery("q")
}
})
termui.Handle("/sys/kbd/C-c", func(termui.Event) {
termui.StopLoop()
slist.selectNothing = true
})
termui.Handle("/sys/kbd/<tab>", func(termui.Event) {
if slist.InNormMode() {
slist.repaint(1)
} else {
offset := slist.search.Next()
slist.uilist.BorderLabel = slist.search.Title()
slist.repaint(offset)
}
})
termui.Handle("/sys/kbd/C-n", moveNext)
termui.Handle("/sys/kbd/<down>", moveNext)
termui.Handle("/sys/kbd/j", func(termui.Event) {
if slist.InNormMode() {
slist.repaint(1)
} else {
slist.appendQuery("j")
}
})
termui.Handle("/sys/kbd/C-p", movePrev)
termui.Handle("/sys/kbd/<up>", movePrev)
termui.Handle("/sys/kbd/k", func(termui.Event) {
if !slist.InSearchMode() {
slist.repaint(-1)
} else {
slist.appendQuery("k")
}
})
// vim page down
termui.Handle("/sys/kbd/C-d", pageDown)
// emacs page down
termui.Handle("/sys/kbd/C-v", pageDown)
// vim page up
termui.Handle("/sys/kbd/C-u", pageUp)
// emacs page up
termui.Handle("/sys/kbd/√", pageUp)
termui.Handle("/sys/kbd/G", func(termui.Event) {
if !slist.InSearchMode() {
slist.termWriter.Write([]byte("G"))
} else {
slist.appendQuery("G")
}
})
termui.Handle("/sys/kbd/g", func(termui.Event) {
if !slist.InSearchMode() {
slist.termWriter.Write([]byte("g"))
} else {
slist.appendQuery("g")
}
})
termui.Handle("/sys/wnd/resize", func(termui.Event) {
slist.repaint(0)
})
termui.Handle("/sys/kbd", func(evt termui.Event) {
kb, ok := evt.Data.(termui.EvtKbd)
if !ok {
return
}
if !slist.InSearchMode() {
switch {
// enter search mode
case kb.KeyStr == "/" || kb.KeyStr == "C-s":
slist.mode = ModeSearch
slist.resetSearch()
slist.uilist.BorderLabel = slist.search.Title()
slist.repaint(0)
case isNumber(kb.KeyStr):
slist.termWriter.Write([]byte(kb.KeyStr))
}
} else {
if kb.KeyStr == "C-8" {
// delete char
searchObj := slist.search
_, size := utf8.DecodeLastRuneInString(searchObj.QueryStr)
searchObj.QueryStr = searchObj.QueryStr[:len(searchObj.QueryStr)-size]
slist.doSearch()
} else if kb.KeyStr == "<space>" {
slist.appendQuery(" ")
} else {
matched, _ := regexp.MatchString(`<.+>|C\-[^c]`, kb.KeyStr)
if !matched {
slist.appendQuery(kb.KeyStr)
}
}
}
})
}
// closeList release resources
func (sl *ComplexSelect) closeList() {
sl.termWriter.Stop()
}
func (slist *ComplexSelect) writeTermLoop() {
for term := range slist.termWriter.DataChan() {
if slist.InNormMode() && term.IsMatched() {
switch term.Name {
case "0gg":
slist.repaint(-slist.selectedIndex)
case "gg":
if idx, err := strconv.Atoi(strings.TrimSuffix(term.Text, "gg")); err == nil {
slist.repaint(idx - 1 - slist.selectedIndex)
}
case "G":
slist.repaint(-slist.selectedIndex - 1)
}
}
}
}
type SearchObj struct {
// filted results indices after searching
SearchResultsIndices []int
// cursor location, index of SearchResultsIndices
SelectedResultIndex int
// current query string
QueryStr string
// base title displayed when searching
SearchTitle string
getOriginalSelectedIndex func() int
}
func (sl *ComplexSelect) resetSearch() {
sl.search.SearchResultsIndices = make([]int, len(sl.items))
sl.search.SelectedResultIndex = 0
sl.search.QueryStr = ""
for i := range sl.items {
sl.search.SearchResultsIndices[i] = i
}
if sl.selectedIndex >= 0 && sl.selectedIndex < len(sl.items) {
sl.search.SelectedResultIndex = sl.selectedIndex
}
}
// render raw string as highlight format
func (sl *ComplexSelect) highlight(raw string, hint string, background bool) string {
so := sl.search
qs := strings.ToLower(so.QueryStr)
raw1 := strings.ToLower(raw)
var result string
for loop := true; loop; loop = false {
// search mode
if matched, start := py.FuzzyContain(raw1, qs); sl.InSearchMode() && start != -1 {
if start < 0 {
if background {
result = fmt.Sprintf("[%s](fg-blue,bg-green)", raw)
} else {
result = raw
}
break
}
end := start + len(matched)
raw1 = ""
if start > 0 {
raw1 += fmt.Sprintf("[%s](fg-magenta,bg-green)", raw[0:start])
}
raw1 += fmt.Sprintf("[%s](fg-white,fg-bold,bg-green)", raw[start:end])
if end < len(raw) {
raw1 += fmt.Sprintf("[%s](fg-magenta,bg-green)", raw[end:len(raw)])
}
if background {
raw1 = strings.Replace(raw1, "fg-magenta", "fg-blue", -1)
} else {
raw1 = strings.Replace(raw1, ",bg-green", "", -1)
}
result = raw1
break
}
// normal display
if background {
result = fmt.Sprintf("[%s](fg-blue,bg-green,fg-underline)", raw)
} else {
result = raw
}
}
if hint != "" && background {
result += fmt.Sprintf(" [%s](fg-white)", hint)
}
return result
}
func (so *SearchObj) Title() string {
if len(so.SearchResultsIndices) > 0 {
return fmt.Sprintf("%s%s [Total %d items, current @%d, Navigation by C-n/C-p/down/up] press ESC exit search", so.SearchTitle, so.QueryStr, len(so.SearchResultsIndices), so.SelectedResultIndex+1)
} else {
return fmt.Sprintf("%s%s Press ESC exit search", so.SearchTitle, so.QueryStr)
}
}
func (so *SearchObj) Next() int {
if so.SelectedResultIndex >= 0 && so.SelectedResultIndex < len(so.SearchResultsIndices) {
so.SelectedResultIndex = (so.SelectedResultIndex + 1) % len(so.SearchResultsIndices)
return so.SearchResultsIndices[so.SelectedResultIndex] - so.getOriginalSelectedIndex()
}
return 0
}
func (so *SearchObj) Current() int {
if so.SelectedResultIndex >= 0 && so.SelectedResultIndex < len(so.SearchResultsIndices) {
return so.SearchResultsIndices[so.SelectedResultIndex] - so.getOriginalSelectedIndex()
}
return 0
}
func (so *SearchObj) Prev() int {
if so.SelectedResultIndex >= 0 && so.SelectedResultIndex < len(so.SearchResultsIndices) {
so.SelectedResultIndex = (so.SelectedResultIndex - 1 + len(so.SearchResultsIndices)) % len(so.SearchResultsIndices)
return so.SearchResultsIndices[so.SelectedResultIndex] - so.getOriginalSelectedIndex()
}
return 0
}
func (slist *ComplexSelect) Show() {
err := termui.Init()
if err != nil {
panic(err)
}
defer termui.Close()
// set max line
if slist.maxLine < termui.TermHeight()-3 {
slist.maxLine = termui.TermHeight() - 3
}
slist.createUI()
defer slist.closeList()
go slist.writeTermLoop()
slist.handleKeyboardEvents()
termui.Loop()
}
func isNumber(num string) bool {
for i := 0; i <= 9; i++ {
if strconv.Itoa(i) == num {
return true
}
}
return false
}
// format command for UI display
func (slist *ComplexSelect) formatCommands() []string {
matchedMap := make(map[int]int)
searchObj := slist.search
for i, j := range searchObj.SearchResultsIndices {
matchedMap[j] = i
}
var strs []string
start := slist.selectedIndex - slist.maxLine + 1
if start < 0 {
start = 0
}
end := start + slist.maxLine - 1
if slist.InSearchMode() {
start = searchObj.SelectedResultIndex - slist.maxLine + 1
if start < 0 {
start = 0
}
end = start + slist.maxLine - 1
}
for i, c := range slist.items {
j, ok := matchedMap[i]
if slist.InSearchMode() {
if !ok || (j < start || j > end) {
continue
}
} else if i < start || i > end {
continue
}
if slist.InNormMode() || (slist.InSearchMode() && ok) {
fmtI := "%02d"
if len(slist.items) > 100 {
fmtI = "%03d"
}
if i == slist.selectedIndex {
strs = append(strs, fmt.Sprintf("["+fmtI+"] %s", i+1, slist.highlight(c, slist.hints[i], true)))
} else {
strs = append(strs, fmt.Sprintf("["+fmtI+"] %s", i+1, slist.highlight(c, "", false)))
}
}
}
return strs
}