welcome/ui/autocomplete.go
2025-03-15 09:12:52 +02:00

52 lines
1.1 KiB
Go

package ui
import (
"strings"
"git.sr.ht/~rockorager/vaxis"
"git.sr.ht/~rockorager/vaxis/widgets/textinput"
)
type Input struct {
model textinput.Model
AutoComplete []string
Placeholder string
}
func complete(m *Input) (rest string) {
if m.model.String() != "" {
for _, comp := range m.AutoComplete {
if strings.HasPrefix(comp, m.model.String()) {
rest = comp[len(m.model.String()):]
break
}
}
} else {
rest = m.Placeholder
}
return
}
func (m *Input) Draw(win vaxis.Window) {
// figure out which thing to complete
rest := complete(m)
m.model.Draw(win)
win.New(len(m.model.String()), 0, win.Width, win.Height).Print(vaxis.Segment{Text: rest, Style: vaxis.Style{Foreground: vaxis.IndexColor(8)}})
}
func (m *Input) Update(event vaxis.Event) {
if key, ok := event.(vaxis.Key); ok && key.EventType == vaxis.EventPress {
switch key.String() {
case "Up", "Down":
if m.model.String() != "" {
m.model.SetContent(m.model.String() + complete(m))
}
}
}
m.model.Update(event)
}
func (m *Input) String() string {
return m.model.String()
}