Left/right arrows move the text input cursor

This commit is contained in:
Christian Rocha 2020-01-18 00:10:03 -05:00
parent 4b64a7cbde
commit 9909356eb7
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018
2 changed files with 53 additions and 16 deletions

View File

@ -10,8 +10,10 @@ type Model struct {
Value string Value string
Cursor string Cursor string
HiddenCursor string HiddenCursor string
Blink bool
BlinkSpeed time.Duration BlinkSpeed time.Duration
blink bool
pos int
} }
type CursorBlinkMsg struct{} type CursorBlinkMsg struct{}
@ -20,10 +22,10 @@ func DefaultModel() Model {
return Model{ return Model{
Prompt: "> ", Prompt: "> ",
Value: "", Value: "",
Cursor: "█", BlinkSpeed: time.Millisecond * 600,
HiddenCursor: " ",
Blink: false, blink: false,
BlinkSpeed: time.Second, pos: 0,
} }
} }
@ -34,28 +36,58 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
switch msg.Type { switch msg.Type {
case tea.KeyBackspace: case tea.KeyBackspace:
if len(m.Value) > 0 { if len(m.Value) > 0 {
m.Value = m.Value[:len(m.Value)-1] 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--
}
return m, nil
case tea.KeyRight:
if m.pos < len(m.Value) {
m.pos++
}
return m, nil
case tea.KeyRune: case tea.KeyRune:
m.Value = m.Value + msg.String() m.Value = m.Value[:m.pos] + msg.String() + m.Value[m.pos:]
m.pos++
return m, nil
default:
return m, nil
} }
case CursorBlinkMsg: case CursorBlinkMsg:
m.Blink = !m.Blink m.blink = !m.blink
}
return m, nil return m, nil
default:
return m, nil
}
} }
func View(model tea.Model) string { func View(model tea.Model) string {
m, _ := model.(Model) m, _ := model.(Model)
cursor := m.Cursor v := m.Value[:m.pos]
if m.Blink { if m.pos < len(m.Value) {
cursor = m.HiddenCursor v += cursor(string(m.Value[m.pos]), m.blink)
v += m.Value[m.pos+1:]
} else {
v += cursor(" ", m.blink)
} }
return m.Prompt + m.Value + cursor return m.Prompt + v
} }
// Style the cursor
func cursor(s string, blink bool) string {
if blink {
return s
}
return tea.Invert(s)
}
// Subscription
func Blink(model tea.Model) tea.Msg { func Blink(model tea.Model) tea.Msg {
m, _ := model.(Model) m, _ := model.(Model)
time.Sleep(m.BlinkSpeed) time.Sleep(m.BlinkSpeed)

5
tea.go
View File

@ -213,6 +213,11 @@ func ClearScreen() {
fmt.Printf(esc + "2J" + esc + "3J" + esc + "1;1H") fmt.Printf(esc + "2J" + esc + "3J" + esc + "1;1H")
} }
// Invert inverts the foreground and background colors of a given string
func Invert(s string) string {
return esc + "7m" + s + esc + "0m"
}
// UseSysLog logs to the system log. This becomes helpful when debugging since // UseSysLog logs to the system log. This becomes helpful when debugging since
// we can't easily print to the terminal since our TUI is occupying it! // we can't easily print to the terminal since our TUI is occupying it!
// //