bubbletea/key.go

68 lines
1.2 KiB
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:46:46 -05:00
// Control keys
const (
2020-01-14 13:47:36 -05:00
keyETX = 3 // break, ctrl+c
keyLF = 9 // line-feed, \n
keyCR = 13 // carriage return, \r
2020-01-10 23:46:46 -05:00
keyESC = 27
keyUS = 31
)
var controlNames = map[int]string{
2020-01-11 11:15:01 -05:00
keyETX: "ctrl+c",
2020-01-14 13:47:36 -05:00
keyLF: "enter",
keyCR: "enter",
2020-01-10 23:46:46 -05:00
keyESC: "esc",
keyUS: "us",
}
var sequenceNames = map[string]string{
2020-01-10 23:12:25 -05:00
"\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:46:46 -05:00
// Get rune
2020-01-10 16:02:04 -05:00
c, _ := utf8.DecodeRune(buf[:])
if c == utf8.RuneError {
return "", errors.New("no such rune")
}
2020-01-10 23:46:46 -05:00
// Is it a control character?
if n == 1 && c <= keyUS {
if s, ok := controlNames[int(c)]; ok {
2020-01-10 23:46:46 -05:00
return s, nil
}
}
// Is it a special sequence, like an arrow key?
if s, ok := sequenceNames[string(buf[:n])]; ok {
2020-01-10 23:46:46 -05:00
return s, nil
}
// Nope, just a regular, ol' rune
2020-01-10 16:02:04 -05:00
return string(c), nil
}