forked from JoaoDanielRufino/go-input-autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.go
More file actions
115 lines (99 loc) · 2.18 KB
/
input.go
File metadata and controls
115 lines (99 loc) · 2.18 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
115
package input_autocomplete
import (
"fmt"
"runtime"
)
type Input struct {
cursor *Cursor
fixedText string
currentText string
isCycling bool
cyclingPos int
matches []string
}
func NewInput(fixedText string) *Input {
return &Input{
cursor: NewCursor(),
fixedText: fixedText,
currentText: "",
isCycling: false,
cyclingPos: 0,
matches: []string{},
}
}
func (i *Input) canDeleteChar() bool {
return i.cursor.GetPosition() >= 1
}
func (i *Input) AddChar(char rune) {
i.isCycling = false
pos := i.cursor.GetPosition()
c := string(char)
if pos == len(i.currentText) {
i.currentText += c
fmt.Print(c)
i.cursor.IncrementPosition()
} else {
aux := len(i.currentText) - pos
i.currentText = i.currentText[:pos] + c + i.currentText[pos:]
i.cursor.SetPosition(len(i.currentText))
i.Print()
i.cursor.MoveLeftNPos(aux)
}
}
func (i *Input) RemoveChar() {
i.isCycling = false
if i.canDeleteChar() {
pos := i.cursor.GetPosition()
aux := len(i.currentText) - pos
i.currentText = i.currentText[:pos-1] + i.currentText[pos:]
i.cursor.SetPosition(len(i.currentText))
i.Print()
i.cursor.MoveLeftNPos(aux)
}
}
func (i *Input) MoveCursorLeft() {
i.isCycling = false
i.cursor.MoveLeft()
}
func (i *Input) MoveCursorRight() {
i.isCycling = false
if i.cursor.GetPosition() < len(i.currentText) {
i.cursor.MoveRight()
}
}
func (i *Input) Autocomplete() {
if !i.isCycling {
i.isCycling = true
i.cyclingPos = 0
i.matches = Autocomplete(i.currentText)
if len(i.matches) <= 1 {
i.isCycling = false
}
}
i.currentText = i.matches[i.cyclingPos]
i.cyclingPos = (i.cyclingPos + 1) % len(i.matches)
i.cursor.SetPosition(len(i.currentText))
i.Print()
}
func (i *Input) RemoveLastSlashIfNeeded() {
os := runtime.GOOS
size := len(i.currentText)
var slash byte
switch os {
case "linux", "darwin":
slash = '/'
case "windows":
slash = '\\'
}
if size > 0 && i.currentText[size-1] == slash {
i.currentText = i.currentText[:size-1]
i.cursor.SetPosition(len(i.currentText))
}
}
func (i *Input) Print() {
fmt.Print("\033[G\033[K")
fmt.Print(i.fixedText + i.currentText)
}
func (i *Input) GetCurrentText() string {
return i.currentText
}