rivo / tview

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

Add ability to select list item programatically #1023

Closed SamWhited closed 3 weeks ago

SamWhited commented 2 months ago

Right now in an application I have a list of items. Some of the items can be selected with a keyboard shortcut other than KeyCR (let's say '1' selects the first item, for the sake of this example). Right now to select the item I have to do something like this (in an InputHandler() implementation, for the sake of this example, but if you were using SetInputHandler you'd have to return the fake event and it's broadly similar):

    if event.Rune() == '1' {
      myList.SetCurrentItem(0)
      myList.InputHandler()(tcell.NewEventKey(tcell.KeyCR, 0, tcell.ModNone), nil)
    }

It would be nice to have a way to either get the "selected" function from the current list item, or a function to select an item just as if enter were pressed without having to manually trigger a keyboard event. This would make the example much easier to read:

    if event.Rune() == '1' {
      myList.SelectItem(0)
    }

I'm happy to implement this if you like the API and need a hand.

EDIT: realized this is a bad example because if it were just '1' you could use the shortcut rune, but in my actual case it's a more complicated key combo and this won't work. Anyways, keep in mind that it's just an example.

Also, went ahead and made a PR just to make it easy to see what the change would be like. Happy to change the API or close it if it doesn't get accepted, of course.

rivo commented 3 weeks ago

The latest commit adds GetSelectedFunc and GetItemSelectedFunc to List. I'm not a fan of invoking the callbacks in a separate function but it's ok to get out what you put in.