Also use arrow keys in example

This commit is contained in:
Christian Rocha 2020-01-10 23:12:25 -05:00
parent bee32ca733
commit c7d28354f7
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018
2 changed files with 18 additions and 4 deletions

View File

@ -20,12 +20,16 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
switch msg { switch msg {
case "j": case "j":
fallthrough
case "down":
m += 1 m += 1
if m > 3 { if m > 3 {
m = 3 m = 3
} }
case "k": case "k":
fallthrough
case "up":
m -= 1 m -= 1
if m < 0 { if m < 0 {
m = 0 m = 0
@ -52,7 +56,7 @@ func view(model tea.Model) string {
) )
return fmt.Sprintf( return fmt.Sprintf(
"What to do today?\n\n%s.\n\n(press j/k to select or q to quit)", "What to do today?\n\n%s\n\n(press j/k or up/down to select, q to quit)",
choices, choices,
) )
} }

16
key.go
View File

@ -9,20 +9,30 @@ import (
// KeyPressMsg contains information about a keypress // KeyPressMsg contains information about a keypress
type KeyPressMsg string type KeyPressMsg string
var keyNames = map[string]string{
"\x1b[A": "up",
"\x1b[B": "down",
"\x1b[C": "right",
"\x1b[D": "left",
}
// ReadKey reads keypress input from a TTY and returns a string representation // ReadKey reads keypress input from a TTY and returns a string representation
// of a key // of a key
func ReadKey(r io.Reader) (string, error) { func ReadKey(r io.Reader) (string, error) {
var buf [256]byte var buf [256]byte
// Read and block // Read and block
_, err := r.Read(buf[:]) n, err := r.Read(buf[:])
if err != nil { if err != nil {
return "", err return "", err
} }
// TODO: non-rune keys like arrows, meta keys, and so on // Was it a special key, like an arrow key?
if s, ok := keyNames[string(buf[:n])]; ok {
return s, nil
}
// Read "normal" key // Nope, just a regular key
c, _ := utf8.DecodeRune(buf[:]) c, _ := utf8.DecodeRune(buf[:])
if c == utf8.RuneError { if c == utf8.RuneError {
return "", errors.New("no such rune") return "", errors.New("no such rune")