introduce default KeyPressed behavior

This commit is contained in:
Timon Ringwald 2022-05-03 17:59:34 +02:00
parent bb68797b02
commit 727d8b28b7
2 changed files with 21 additions and 0 deletions

View File

@ -39,6 +39,8 @@ func NewScreen(root View) (*Screen, error) {
redrawCh: make(chan struct{}, 1), redrawCh: make(chan struct{}, 1),
} }
s.KeyPressed = CloseOnCtrlC(s)
go s.eventloop() go s.eventloop()
go s.drawloop() go s.drawloop()

View File

@ -3,6 +3,7 @@ package tui
import ( import (
"strings" "strings"
"github.com/gdamore/tcell"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
) )
@ -113,3 +114,21 @@ func ConstrainBufferToAnchor(buf *ViewBuffer, anchor Anchor, width, height int)
return buf.Sub(buf.Width()-width, buf.Height()-height, width, height) return buf.Sub(buf.Width()-width, buf.Height()-height, width, height)
} }
} }
// CloseOnCtrlC returns a KeyPress handler which closes the screen when Ctrl-C is pressed.
// This is the default behavior for all new screens.
// CloseOnCtrlC is a shorthand for CloseOnKeyPressed(screen, tcell.KeyCtrlC)
func CloseOnCtrlC(screen *Screen) func(event *KeyEvent) (consumed bool) {
return CloseOnKeyPressed(screen, tcell.KeyCtrlC)
}
// CloseOnKeyPressed returns a KeyPress handler which closes the screen when the given key is pressed.
func CloseOnKeyPressed(screen *Screen, key tcell.Key) func(event *KeyEvent) (consumed bool) {
return func(event *KeyEvent) (consumed bool) {
if event.Key() == key {
screen.Stop()
return false
}
return true
}
}