rivo / tview

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

Form.SetFocus(item index) does not seem to work #922

Closed elsni closed 1 year ago

elsni commented 1 year ago

In a form, I want to move between FormItems using PgUp and PgDown in addition to Tab/Shift-Tab. So I implemented an InputCapture func to do this, but setFocus does not seem to do anything. Maybe I made a stupid mistake.

used version: commit 7c9e464

code:

func TestForm() {
    app := tview.NewApplication()
    form := tview.NewForm().
        AddInputField("Monday", "Test", 40, nil, nil).
        AddInputField("Tuesday", "Test", 40, nil, nil).
        AddInputField("Wednesday", "Test", 40, nil, nil).
        AddInputField("Thursday", "Test", 40, nil, nil)
    form.AddButton("Quit", func() {
        app.Stop()
    })
    form.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
        switch event.Key() {
        case tcell.KeyEscape:
            app.Stop()
            return nil
        case tcell.KeyPgDn:
            fallthrough
        case tcell.KeyPgUp:
            maxidx := form.GetFormItemCount() - 1
            fidx, _ := form.GetFocusedItemIndex()
            // focused itemindex is -1 when a button is focused
            if fidx > -1 {
                if event.Key() == tcell.KeyPgDn {
                    fidx += 1
                    if fidx > maxidx {
                        fidx = 0
                    }
                }
                if event.Key() == tcell.KeyPgUp {
                    fidx -= 1
                    if fidx < 0 {
                        fidx = maxidx
                    }
                }

                form.SetFocus(fidx)
            }
            return nil
        }

        return event
    })
    form.SetRect(0, 0, 56, 16)
    if err := app.SetRoot(form, false).SetFocus(form).EnableMouse(true).Run(); err != nil {
        panic(err)
    }
}
rivo commented 1 year ago

Good catch. Thank you for letting me know. The latest commit should fix this.