bubbletea/key.go

43 lines
752 B
Go
Raw Normal View History

2020-01-10 16:02:04 -05:00
package tea
import (
"errors"
"io"
"unicode/utf8"
)
// KeyPressMsg contains information about a keypress
type KeyPressMsg string
2020-01-10 23:12:25 -05:00
var keyNames = map[string]string{
"\x1b[A": "up",
"\x1b[B": "down",
"\x1b[C": "right",
"\x1b[D": "left",
}
2020-01-10 16:02:04 -05:00
// 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
2020-01-10 23:12:25 -05:00
n, err := r.Read(buf[:])
2020-01-10 16:02:04 -05:00
if err != nil {
return "", err
}
2020-01-10 23:12:25 -05:00
// Was it a special key, like an arrow key?
if s, ok := keyNames[string(buf[:n])]; ok {
return s, nil
}
2020-01-10 16:02:04 -05:00
2020-01-10 23:12:25 -05:00
// Nope, just a regular key
2020-01-10 16:02:04 -05:00
c, _ := utf8.DecodeRune(buf[:])
if c == utf8.RuneError {
return "", errors.New("no such rune")
}
return string(c), nil
}