github.com/wtfutil/wtf@v0.43.0/modules/grafana/widget.go (about) 1 package grafana 2 3 import ( 4 "fmt" 5 "strconv" 6 7 "github.com/rivo/tview" 8 "github.com/wtfutil/wtf/utils" 9 "github.com/wtfutil/wtf/view" 10 ) 11 12 type Widget struct { 13 view.TextWidget 14 15 Client *Client 16 Alerts []Alert 17 Err error 18 Selected int 19 20 settings *Settings 21 } 22 23 func NewWidget(tviewApp *tview.Application, redrawChan chan bool, _ *tview.Pages, settings *Settings) *Widget { 24 widget := Widget{ 25 TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.Common), 26 27 Client: NewClient(settings), 28 Selected: -1, 29 30 settings: settings, 31 } 32 33 widget.initializeKeyboardControls() 34 widget.View.SetRegions(true) 35 36 return &widget 37 } 38 39 /* -------------------- Exported Functions -------------------- */ 40 41 func (widget *Widget) Refresh() { 42 alerts, err := widget.Client.Alerts() 43 if err != nil { 44 widget.Err = err 45 widget.Alerts = nil 46 } else { 47 widget.Err = nil 48 widget.Alerts = alerts 49 } 50 51 widget.Redraw(widget.content) 52 } 53 54 // GetSelected returns the index of the currently highlighted item as an int 55 func (widget *Widget) GetSelected() int { 56 if widget.Selected < 0 { 57 return 0 58 } 59 return widget.Selected 60 } 61 62 // Next cycles the currently highlighted text down 63 func (widget *Widget) Next() { 64 widget.Selected++ 65 if widget.Selected >= len(widget.Alerts) { 66 widget.Selected = 0 67 } 68 widget.View.Highlight(strconv.Itoa(widget.Selected)) 69 widget.View.ScrollToHighlight() 70 } 71 72 // Prev cycles the currently highlighted text up 73 func (widget *Widget) Prev() { 74 widget.Selected-- 75 if widget.Selected < 0 { 76 widget.Selected = len(widget.Alerts) - 1 77 } 78 widget.View.Highlight(strconv.Itoa(widget.Selected)) 79 widget.View.ScrollToHighlight() 80 } 81 82 // Unselect stops highlighting the text and jumps the scroll position to the top 83 func (widget *Widget) Unselect() { 84 widget.Selected = -1 85 widget.View.Highlight() 86 widget.View.ScrollToBeginning() 87 } 88 89 /* -------------------- Unexported Functions -------------------- */ 90 91 func (widget *Widget) openAlert() { 92 currentSelection := widget.View.GetHighlights() 93 if widget.Selected >= 0 && currentSelection[0] != "" { 94 url := widget.Alerts[widget.GetSelected()].URL 95 if url[0] == '/' { 96 url = fmt.Sprintf("%s%s", widget.settings.baseURI, url) 97 } 98 utils.OpenFile(url) 99 } 100 }