1
0
mirror of https://github.com/mum4k/termdash.git synced 2025-04-25 13:48:50 +08:00

Add OnChange event handler to TextInput widget

This commit is contained in:
LQR471814 2023-01-29 10:24:32 -08:00
parent 0aac8f46e0
commit 2cbce1c330
3 changed files with 24 additions and 1 deletions

View File

@ -274,6 +274,9 @@ type fieldEditor struct {
// width is the width of the text input field last time viewFor was called.
width int
// onChange if provided is the handler called when fieldData changes
onChange ChangeFn
}
// newFieldEditor returns a new fieldEditor instance.
@ -338,6 +341,9 @@ func (fe *fieldEditor) insert(r rune) {
}
fe.data.insertAt(fe.curDataPos, r)
fe.curDataPos++
if fe.onChange != nil {
fe.onChange(string(fe.data))
}
}
// delete deletes the rune at the current position of the cursor.
@ -347,6 +353,9 @@ func (fe *fieldEditor) delete() {
return
}
fe.data.deleteAt(fe.curDataPos)
if fe.onChange != nil {
fe.onChange(string(fe.data))
}
}
// deleteBefore deletes the rune that is immediately to the left of the cursor.

View File

@ -63,6 +63,7 @@ type options struct {
filter FilterFn
onSubmit SubmitFn
onChange ChangeFn
clearOnSubmit bool
exclusiveKeyboardOnFocus bool
}
@ -269,6 +270,19 @@ func OnSubmit(fn SubmitFn) Option {
})
}
// ChangeFn if provided is called when the content of the text input field changes,
// the argument data contains all the text in the field.
//
// The callback function must be thread-safe as the keyboard event that
// triggers the submission comes from a separate goroutine.
type ChangeFn func(data string)
func OnChange(fn ChangeFn) Option {
return option(func(opts *options) {
opts.onChange = fn
})
}
// ClearOnSubmit sets the text input to be cleared when a submit of the content
// is triggered by the user pressing the Enter key.
func ClearOnSubmit() Option {

View File

@ -73,7 +73,7 @@ func New(opts ...Option) (*TextInput, error) {
editor: newFieldEditor(),
opts: opt,
}
ti.editor.onChange = opt.onChange
for _, r := range ti.opts.defaultText {
ti.editor.insert(r)
}