rivo / tview

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

Help: Is there an example somewheres of a table where you can highlight and select an entire row? #1005

Open SimplySeth opened 4 months ago

SimplySeth commented 4 months ago

Is there an example somewheres of a table where you can highlight and select an entire row?

This is what I'm trying so far:

func TableView(app *tview.Application) *tview.Table {
    blob := readJsonFile()
    data := blob["result"][0:10] # perhaps I have to implement paging
    headers := mkTaskHeaders(blob)
    rowCount := len(data)
    table := tview.NewTable().
        SetBorders(true).
        SetBordersColor(tcell.ColorYellow)
    for r := 0; r < rowCount; r++ {
        for i, c := range headers {
            if r == 0 {
                table.SetCell(r, i, tview.NewTableCell(mkTitle(c)).
                    SetAlign(tview.AlignCenter))
            }
            if c == "short_description" {
                table.SetCell(
                    r+1, i, tview.NewTableCell(data[r][c]).
                        SetAlign(tview.AlignLeft))
            } else {
                table.SetCell(
                    r+1, i, tview.NewTableCell(data[r][c]).
                        SetAlign(tview.AlignCenter))
            }
        }
        table.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
            selected, _ := table.GetSelectable()

            if event.Key() == tcell.KeyEnter {
                table.SetSelectable(true, true)
            }
            if selected && event.Key() == tcell.KeyEnter {
                row, col := table.GetSelection()
                cell := table.GetCell(row, col).
                    SetBackgroundColor(tcell.ColorYellow)
                fmt.Println(cell.Reference)
                fmt.Println(cell.Attributes)
                fmt.Println(cell.Text)
            }
            return event
        })

    }
    return table
}
rivo commented 3 months ago

From what I can see, you don't need to call SetInputCapture(), especially not for each row. Just call table.SetSelectable(true, false) once when initializing your table. Use SetSelectedFunc() to listen for selections (Enter key). It's all there in the documentation.

For an example of this, check out the demo presentation included in the package. The code for selecting rows is here: https://github.com/rivo/tview/blob/65571ae51e71d29a5e8a0082667b778939cca29f/demos/presentation/table.go#L311