rivo / tview

Terminal UI library with rich, interactive widgets — written in Golang
MIT License
11.14k stars 575 forks source link

InputField calls `changed` function three times when using `.SetText` #908

Closed vitorqb closed 1 year ago

vitorqb commented 1 year ago

Hi :wave:, thanks for this great library.

Using the latest version (github.com/rivo/tview v0.0.0-20231031172508-2dfe06011790) I have found an inconsistent behavior for InputField. I believe it was introduced at commit 6416d6b.

When calling .SetText on an InputField, the changed function gets called three times.

Here is a repo that reproduces the issue: https://github.com/vitorqb/tview-bug

Here is the base snippet:

package main

import (
    "fmt"

    "github.com/rivo/tview"
)

var ChangeCalls []string

func main() {
    inputField := tview.NewInputField()
    inputField.SetChangedFunc(func(text string) {
        ChangeCalls = append(ChangeCalls, text)
    })
    inputField.SetText("Hello, World!")
    fmt.Println("Text: " + inputField.GetText())
    fmt.Println("ChangeCalls: " + fmt.Sprintf("%v", ChangeCalls))   
    fmt.Println("ChangeCallCount: " + fmt.Sprintf("%v", len(ChangeCalls)))
}

Which prints

Text: Hello, World!
ChangeCalls: [Hello, World! Hello, World! Hello, World!]
ChangeCallCount: 3

As you can see the function given to SetChangedFunc was called 3 times with the same string, even though the input just changed once (call to .SetText). I expected it to be called only once.

rivo commented 1 year ago

Thank you for letting me know about this. Yes, there were indeed a few too many calls to the "changed" callback in the code. The latest commit should fix this.