github.com/wtfutil/wtf@v0.43.0/modules/stocks/yfinance/widget.go (about)

     1  package yfinance
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  
     7  	"github.com/jedib0t/go-pretty/v6/table"
     8  	"github.com/rivo/tview"
     9  	"github.com/wtfutil/wtf/view"
    10  )
    11  
    12  // Widget is the container for your module's data
    13  type Widget struct {
    14  	view.TextWidget
    15  
    16  	settings *Settings
    17  }
    18  
    19  // NewWidget creates and returns an instance of Widget
    20  func NewWidget(tviewApp *tview.Application, redrawChan chan bool, settings *Settings) *Widget {
    21  	widget := Widget{
    22  		TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.common),
    23  
    24  		settings: settings,
    25  	}
    26  
    27  	return &widget
    28  }
    29  
    30  /* -------------------- Exported Functions -------------------- */
    31  
    32  // Refresh updates the onscreen contents of the widget
    33  func (widget *Widget) Refresh() {
    34  
    35  	// The last call should always be to the display function
    36  	widget.display()
    37  }
    38  
    39  /* -------------------- Unexported Functions -------------------- */
    40  
    41  func (widget *Widget) content() string {
    42  	yquotes := quotes(widget.settings.symbols)
    43  
    44  	colors := map[string]string{
    45  		"bigup":   widget.settings.colors.bigup,
    46  		"up":      widget.settings.colors.up,
    47  		"drop":    widget.settings.colors.drop,
    48  		"bigdrop": widget.settings.colors.bigdrop,
    49  	}
    50  
    51  	if widget.settings.sort {
    52  		sort.SliceStable(yquotes, func(i, j int) bool { return yquotes[i].MarketChangePct > yquotes[j].MarketChangePct })
    53  	}
    54  
    55  	t := table.NewWriter()
    56  	t.SetStyle(tableStyle())
    57  	for _, yq := range yquotes {
    58  		t.AppendRow([]interface{}{
    59  			GetMarketIcon(yq.MarketState),
    60  			yq.Symbol,
    61  			fmt.Sprintf("%8.2f %s", yq.MarketPrice, yq.Currency),
    62  			GetTrendIcon(yq.Trend),
    63  			fmt.Sprintf("[%s]%+6.2f (%+5.2f%%)", colors[yq.Trend], yq.MarketChange, yq.MarketChangePct),
    64  		})
    65  	}
    66  
    67  	return t.Render()
    68  }
    69  
    70  func (widget *Widget) display() {
    71  	widget.Redraw(func() (string, string, bool) {
    72  		return widget.CommonSettings().Title, widget.content(), false
    73  	})
    74  }