Trigger ExitChecker on pressed keys (#162)

* prompt.go handleKeyBinding can indicate one should Exit if an exit checker function is set

* Use new name exitChecker instead of old exitor

* ExitChecker API change: breakline bool

- breakline true means the executor has been called: check for exit
- breakline false means no executor, just a character typed: check for
exit
This commit is contained in:
VonC 2020-02-22 05:16:28 +01:00 committed by GitHub
parent 0d097872c2
commit 39d1a739c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -12,9 +12,11 @@ import (
type Executor func(string)
// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop.
// User input means: selecting/typing an entry, then <return>, and the executor is called.
// Then, if said entry content matches the ExitChecker function criteria, exit go-prompt (not the overall Go program)
type ExitChecker func(string) bool
// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria:
// - immediate exit (if breakline is false) without executor called
// - exit after typing <return> (meaning breakline is true), and the executor is called first, before exit.
// Exit means exit go-prompt (not the overall Go program)
type ExitChecker func(in string, breakline bool) bool
// Completer should return the suggest item from Document.
type Completer func(Document) []Suggest
@ -85,7 +87,7 @@ func (p *Prompt) Run() {
p.renderer.Render(p.buf, p.completion)
if p.exitChecker != nil && p.exitChecker(e.input) {
if p.exitChecker != nil && p.exitChecker(e.input, true) {
p.skipTearDown = true
return
}
@ -155,7 +157,7 @@ func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {
p.buf.InsertText(string(b), false, true)
}
p.handleKeyBinding(key)
shouldExit = p.handleKeyBinding(key)
return
}
@ -185,7 +187,8 @@ func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) {
}
}
func (p *Prompt) handleKeyBinding(key Key) {
func (p *Prompt) handleKeyBinding(key Key) bool {
shouldExit := false
for i := range commonKeyBindings {
kb := commonKeyBindings[i]
if kb.Key == key {
@ -209,6 +212,10 @@ func (p *Prompt) handleKeyBinding(key Key) {
kb.Fn(p.buf)
}
}
if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) {
shouldExit = true
}
return shouldExit
}
func (p *Prompt) handleASCIICodeBinding(b []byte) bool {