From c7d28354f753cc0331fff813df881712d2a5c414 Mon Sep 17 00:00:00 2001 From: Christian Rocha Date: Fri, 10 Jan 2020 23:12:25 -0500 Subject: [PATCH] Also use arrow keys in example --- example/main.go | 6 +++++- key.go | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/example/main.go b/example/main.go index b2c4dbf..9a212e8 100644 --- a/example/main.go +++ b/example/main.go @@ -20,12 +20,16 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) { switch msg { case "j": + fallthrough + case "down": m += 1 if m > 3 { m = 3 } case "k": + fallthrough + case "up": m -= 1 if m < 0 { m = 0 @@ -52,7 +56,7 @@ func view(model tea.Model) string { ) 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, ) } diff --git a/key.go b/key.go index 5d38bb3..0bbd0a3 100644 --- a/key.go +++ b/key.go @@ -9,20 +9,30 @@ import ( // KeyPressMsg contains information about a keypress 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 // of a key func ReadKey(r io.Reader) (string, error) { var buf [256]byte // Read and block - _, err := r.Read(buf[:]) + n, err := r.Read(buf[:]) if err != nil { 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[:]) if c == utf8.RuneError { return "", errors.New("no such rune")