-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.go
More file actions
114 lines (98 loc) · 2.49 KB
/
select.go
File metadata and controls
114 lines (98 loc) · 2.49 KB
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
package input
import (
"atomicgo.dev/keyboard/keys"
"fmt"
"github.com/liuuner/go-cli-input/colors"
"github.com/liuuner/go-cli-input/cursor"
)
type SelectState[T any] struct {
items []T
GetName func(T) string
GetColor func(T) colors.Formatter
cursorRune rune
cursorPos int
}
func NewSelect[T any](prompt string, items []T, getName func(T) string) Input[SelectState[T]] {
i := newInput[SelectState[T]]()
state := SelectState[T]{
items: items,
cursorRune: '❯',
cursorPos: 0,
GetName: getName,
}
return Input[SelectState[T]]{
render: renderSelect[T],
handleInput: handleSelect[T],
close: closeSelect[T],
userPrompt: prompt,
inputPrompt: "› - Use arrow-keys. Return to submit.",
hasPrompt: i.hasPrompt,
hasSummary: i.hasSummary,
failedString: i.failedString,
completedString: i.completedString,
promptString: i.promptString,
state: state,
}
}
func renderSelect[T any](s *SelectState[T], rerender bool) {
if rerender {
// Move cursor to top
cursor.UpN(len(s.items) - 1)
} else {
cursor.Hide()
}
for index, item := range s.items {
var newline = "\n"
if index == len(s.items)-1 {
// Adding a new line on the last option will move the cursor position out of range
// For out redrawing
newline = ""
}
menuItemText := s.GetName(item)
if s.GetColor != nil {
menuItemText = s.GetColor(item)(menuItemText)
}
cursorString := " "
if index == s.cursorPos { // for color or other effects
cursorString = col.Cyan(string(s.cursorRune), " ")
menuItemText = col.Underline(menuItemText)
}
fmt.Printf("\r%s %s%s", cursorString, menuItemText, newline)
}
}
func handleSelect[T any](s *SelectState[T], key keys.Key) (stop bool, err error) {
switch key.Code {
case keys.Left:
s.cursorPos = 0
case keys.Right:
s.cursorPos = len(s.items) - 1
case keys.Up:
s.cursorPos--
s.keepPosInBoundaries()
case keys.Down:
s.cursorPos++
s.keepPosInBoundaries()
case keys.Enter:
stop, err = true, nil
}
return
}
func closeSelect[T any](s *SelectState[T], err error) (summary string) {
cursor.ClearLine()
for i := 0; i < len(s.items)-1; i++ {
cursor.Up()
cursor.ClearLine()
}
summary = s.GetName(s.items[s.cursorPos])
if err != nil {
summary = err.Error()
}
cursor.Show()
return
}
func (s *SelectState[T]) Resolve() T {
return s.items[s.cursorPos]
}
func (s *SelectState[T]) keepPosInBoundaries() {
s.cursorPos = (s.cursorPos + len(s.items)) % len(s.items)
}