-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_input.go
99 lines (81 loc) · 2.59 KB
/
selection_input.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
package main
import (
"strings"
)
/*/ / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
// EXAMPLE USAGE
fuzzyPicker := SelectionInput{} // (state.FuzzyPicker is an instance of `SelectionInput`, fyi)
fuzzyPicker.StringItems = []string{}
fuzzyPicker.Items = []interface{}
// Add corresponding items to `Items` and `StringItems`
// Their lengths need to be the same.
for i := 0; i < 10; i++ {
fuzzyPicker.Items = append(state.FuzzyPicker.Items, i)
fuzzyPicker.StringItems = append(state.FuzzyPicker.Items, string(i))
}
// Show the fuzzy picker, and provide a callback to be called when the user selects an item.
fuzzyPicker.Show(func(state *State) {
log.Printf("I'm printed when the user selectd something.")
log.Printf("Selected index = %d", state.FuzzyPicker.SelectedItem)
})
/ / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /*/
// A struct that wraps a collection of string items and norma items, and sorts both based on the
// closeness of each of `StringItems` to `Needle`.
type SelectionInput struct {
Visible bool
Items []interface{}
StringItems []string
Needle string
OnSelected func(*State)
OnResort func(*State)
SelectedItem int
BottomItem int
// Number of characters at the start of the search string to disregard
ThrowAwayPrefix int
}
func (p SelectionInput) Len() int {
return len(p.StringItems)
}
func (p SelectionInput) Less(i, j int) bool {
iItem := p.StringItems[i]
jItem := p.StringItems[j]
return p.Rank(iItem) > p.Rank(jItem)
}
func (p SelectionInput) Swap(i, j int) {
p.Items[i], p.Items[j] = p.Items[j], p.Items[i]
p.StringItems[i], p.StringItems[j] = p.StringItems[j], p.StringItems[i]
}
func (p SelectionInput) Rank(item string) int {
var delta int = 0
if len(item) > 0 && item[0] == '.' {
delta -= 20
}
if len(p.Needle) < p.ThrowAwayPrefix {
return strings.Index(item, p.Needle) + delta
} else {
return strings.Index(item, p.Needle[p.ThrowAwayPrefix:]) + delta
}
}
// Show the fuzzy picker
func (p *SelectionInput) Show(callbackOnSelected func(*State)) {
p.Visible = true
p.OnSelected = callbackOnSelected
p.SelectedItem = 0
p.BottomItem = 0
}
func (p *SelectionInput) Resort(callbackOnResort func(*State)) {
p.OnResort = callbackOnResort
}
// Hide the fuzzy picker and reset to initial state
func (p *SelectionInput) Hide() {
p.Visible = false
p.Items = []interface{}{}
p.StringItems = []string{}
p.ThrowAwayPrefix = 0
p.OnSelected = nil
p.OnResort = nil
}
type SelectionInputConnectionChannelItem struct {
Channel string
Connection string
}