mirror of
https://github.com/taigrr/bubbletea.git
synced 2026-04-02 02:59:09 -07:00
Also use arrow keys in example
This commit is contained in:
@@ -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,
|
||||
)
|
||||
}
|
||||
|
||||
16
key.go
16
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")
|
||||
|
||||
Reference in New Issue
Block a user