github.com/wtfutil/wtf@v0.43.0/view/scrollable_widget.go (about)

     1  package view
     2  
     3  import (
     4  	"strconv"
     5  
     6  	"github.com/rivo/tview"
     7  	"github.com/wtfutil/wtf/cfg"
     8  )
     9  
    10  type ScrollableWidget struct {
    11  	TextWidget
    12  
    13  	Selected       int
    14  	maxItems       int
    15  	RenderFunction func()
    16  }
    17  
    18  func NewScrollableWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, commonSettings *cfg.Common) ScrollableWidget {
    19  	widget := ScrollableWidget{
    20  		TextWidget: NewTextWidget(tviewApp, redrawChan, pages, commonSettings),
    21  	}
    22  
    23  	widget.Unselect()
    24  	widget.View.SetScrollable(true)
    25  	widget.View.SetRegions(true)
    26  
    27  	return widget
    28  }
    29  
    30  /* -------------------- Exported Functions -------------------- */
    31  
    32  func (widget *ScrollableWidget) SetRenderFunction(displayFunc func()) {
    33  	widget.RenderFunction = displayFunc
    34  }
    35  
    36  func (widget *ScrollableWidget) SetItemCount(items int) {
    37  	widget.maxItems = items
    38  	if items == 0 {
    39  		widget.Selected = -1
    40  	}
    41  }
    42  
    43  func (widget *ScrollableWidget) GetSelected() int {
    44  	return widget.Selected
    45  }
    46  
    47  func (widget *ScrollableWidget) RowColor(idx int) string {
    48  	if widget.View.HasFocus() && (idx == widget.Selected) {
    49  		return widget.CommonSettings().DefaultFocusedRowColor()
    50  	}
    51  
    52  	return widget.CommonSettings().RowColor(idx)
    53  }
    54  
    55  func (widget *ScrollableWidget) Next() {
    56  	widget.Selected++
    57  	if widget.Selected >= widget.maxItems {
    58  		widget.Selected = 0
    59  	}
    60  	if widget.maxItems == 0 {
    61  		widget.Selected = -1
    62  	}
    63  	widget.RenderFunction()
    64  }
    65  
    66  func (widget *ScrollableWidget) Prev() {
    67  	widget.Selected--
    68  	if widget.Selected < 0 {
    69  		widget.Selected = widget.maxItems - 1
    70  	}
    71  	if widget.maxItems == 0 {
    72  		widget.Selected = -1
    73  	}
    74  	widget.RenderFunction()
    75  }
    76  
    77  func (widget *ScrollableWidget) Unselect() {
    78  	widget.Selected = -1
    79  	if widget.RenderFunction != nil {
    80  		widget.RenderFunction()
    81  	}
    82  }
    83  
    84  func (widget *ScrollableWidget) Redraw(data func() (string, string, bool)) {
    85  	widget.TextWidget.Redraw(data)
    86  
    87  	widget.View.Highlight(strconv.Itoa(widget.Selected))
    88  	widget.View.ScrollToHighlight()
    89  }