bubbletea/input/input.go

64 lines
1.0 KiB
Go
Raw Normal View History

2020-01-17 22:21:51 -05:00
package input
import (
"tea"
"time"
)
type Model struct {
Prompt string
Value string
Cursor string
HiddenCursor string
Blink bool
BlinkSpeed time.Duration
}
type CursorBlinkMsg struct{}
func DefaultModel() Model {
return Model{
Prompt: "> ",
Value: "",
Cursor: "█",
HiddenCursor: " ",
Blink: false,
BlinkSpeed: time.Second,
}
}
2020-01-17 23:27:54 -05:00
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
2020-01-17 22:21:51 -05:00
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyBackspace:
if len(m.Value) > 0 {
m.Value = m.Value[:len(m.Value)-1]
}
2020-01-17 22:21:51 -05:00
case tea.KeyRune:
m.Value = m.Value + msg.String()
}
case CursorBlinkMsg:
m.Blink = !m.Blink
}
return m, nil
}
func View(model tea.Model) string {
m, _ := model.(Model)
cursor := m.Cursor
2020-01-17 23:27:54 -05:00
if m.Blink {
cursor = m.HiddenCursor
}
2020-01-17 22:21:51 -05:00
return m.Prompt + m.Value + cursor
}
func Blink(model tea.Model) tea.Msg {
2020-01-17 23:27:54 -05:00
m, _ := model.(Model)
time.Sleep(m.BlinkSpeed)
2020-01-17 22:21:51 -05:00
return CursorBlinkMsg{}
}