2020-01-17 22:21:51 -05:00
|
|
|
package input
|
|
|
|
|
|
|
|
import (
|
|
|
|
"tea"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Model struct {
|
|
|
|
Prompt string
|
|
|
|
Value string
|
|
|
|
Cursor string
|
|
|
|
HiddenCursor string
|
|
|
|
BlinkSpeed time.Duration
|
2020-01-18 00:10:03 -05:00
|
|
|
|
|
|
|
blink bool
|
|
|
|
pos int
|
2020-01-17 22:21:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type CursorBlinkMsg struct{}
|
|
|
|
|
|
|
|
func DefaultModel() Model {
|
|
|
|
return Model{
|
2020-01-18 00:10:03 -05:00
|
|
|
Prompt: "> ",
|
|
|
|
Value: "",
|
|
|
|
BlinkSpeed: time.Millisecond * 600,
|
|
|
|
|
|
|
|
blink: false,
|
|
|
|
pos: 0,
|
2020-01-17 22:21:51 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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:
|
2020-01-17 22:28:17 -05:00
|
|
|
if len(m.Value) > 0 {
|
2020-01-18 00:10:03 -05:00
|
|
|
m.Value = m.Value[:m.pos-1] + m.Value[m.pos:]
|
|
|
|
m.pos--
|
|
|
|
}
|
|
|
|
return m, nil
|
|
|
|
case tea.KeyLeft:
|
|
|
|
if m.pos > 0 {
|
|
|
|
m.pos--
|
2020-01-17 22:28:17 -05:00
|
|
|
}
|
2020-01-18 00:10:03 -05:00
|
|
|
return m, nil
|
|
|
|
case tea.KeyRight:
|
|
|
|
if m.pos < len(m.Value) {
|
|
|
|
m.pos++
|
|
|
|
}
|
|
|
|
return m, nil
|
2020-01-17 22:21:51 -05:00
|
|
|
case tea.KeyRune:
|
2020-01-18 00:10:03 -05:00
|
|
|
m.Value = m.Value[:m.pos] + msg.String() + m.Value[m.pos:]
|
|
|
|
m.pos++
|
|
|
|
return m, nil
|
|
|
|
default:
|
|
|
|
return m, nil
|
2020-01-17 22:21:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
case CursorBlinkMsg:
|
2020-01-18 00:10:03 -05:00
|
|
|
m.blink = !m.blink
|
|
|
|
return m, nil
|
2020-01-17 22:21:51 -05:00
|
|
|
|
2020-01-18 00:10:03 -05:00
|
|
|
default:
|
|
|
|
return m, nil
|
|
|
|
}
|
2020-01-17 22:21:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func View(model tea.Model) string {
|
|
|
|
m, _ := model.(Model)
|
2020-01-18 00:10:03 -05:00
|
|
|
v := m.Value[:m.pos]
|
|
|
|
if m.pos < len(m.Value) {
|
|
|
|
v += cursor(string(m.Value[m.pos]), m.blink)
|
|
|
|
v += m.Value[m.pos+1:]
|
|
|
|
} else {
|
|
|
|
v += cursor(" ", m.blink)
|
|
|
|
}
|
|
|
|
return m.Prompt + v
|
|
|
|
}
|
|
|
|
|
|
|
|
// Style the cursor
|
|
|
|
func cursor(s string, blink bool) string {
|
|
|
|
if blink {
|
|
|
|
return s
|
2020-01-17 23:27:54 -05:00
|
|
|
}
|
2020-01-18 00:10:03 -05:00
|
|
|
return tea.Invert(s)
|
2020-01-17 22:21:51 -05:00
|
|
|
}
|
|
|
|
|
2020-01-18 00:10:03 -05:00
|
|
|
// Subscription
|
2020-01-17 22:21:51 -05:00
|
|
|
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{}
|
|
|
|
}
|