diff --git a/widgets/textinput/editor.go b/widgets/textinput/editor.go index 8df4d76..00f23bb 100644 --- a/widgets/textinput/editor.go +++ b/widgets/textinput/editor.go @@ -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. diff --git a/widgets/textinput/options.go b/widgets/textinput/options.go index 995d029..572365e 100644 --- a/widgets/textinput/options.go +++ b/widgets/textinput/options.go @@ -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 { diff --git a/widgets/textinput/textinput.go b/widgets/textinput/textinput.go index 393e27d..7efbe80 100644 --- a/widgets/textinput/textinput.go +++ b/widgets/textinput/textinput.go @@ -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) }