github.com/wtfutil/wtf@v0.43.0/modules/devto/widget.go (about) 1 package devto 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/VictorAvelar/devto-api-go/devto" 8 "github.com/rivo/tview" 9 10 "github.com/wtfutil/wtf/utils" 11 "github.com/wtfutil/wtf/view" 12 ) 13 14 type Widget struct { 15 view.ScrollableWidget 16 17 articles []devto.ListedArticle 18 settings *Settings 19 err error 20 } 21 22 func NewWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, settings *Settings) *Widget { 23 widget := &Widget{ 24 ScrollableWidget: view.NewScrollableWidget(tviewApp, redrawChan, pages, settings.Common), 25 26 settings: settings, 27 } 28 29 widget.SetRenderFunction(widget.Render) 30 widget.View.SetScrollable(true) 31 widget.initializeKeyboardControls() 32 33 return widget 34 } 35 36 func (widget *Widget) Refresh() { 37 if widget.Disabled() { 38 return 39 } 40 41 ctx := context.Background() 42 wCfg, _ := devto.NewConfig(false, "") 43 44 c, _ := devto.NewClient(ctx, wCfg, nil, devto.BaseURL) 45 46 options := devto.ArticleListOptions{ 47 Tags: widget.settings.contentTag, 48 Username: widget.settings.contentUsername, 49 State: widget.settings.contentState, 50 } 51 52 articles, err := c.Articles.List(ctx, options) 53 if err != nil { 54 widget.err = err 55 widget.articles = nil 56 widget.SetItemCount(0) 57 } else { 58 var displayArticles []devto.ListedArticle 59 var l int 60 if len(articles) < widget.settings.numberOfArticles { 61 l = len(articles) 62 } else { 63 l = widget.settings.numberOfArticles - 1 64 } 65 for i, art := range articles { 66 if i > l { 67 break 68 } 69 displayArticles = append(displayArticles, art) 70 } 71 widget.articles = displayArticles 72 widget.SetItemCount(len(displayArticles)) 73 } 74 75 widget.Render() 76 } 77 78 // Render sets up the widget data for redrawing to the screen 79 func (widget *Widget) Render() { 80 widget.Redraw(widget.content) 81 } 82 83 /* -------------------- Unexported Functions -------------------- */ 84 85 func (widget *Widget) content() (string, string, bool) { 86 title := fmt.Sprintf("%s - %s stories", widget.CommonSettings().Title, widget.settings.contentTag) 87 88 if widget.err != nil { 89 return title, widget.err.Error(), true 90 } 91 92 articles := widget.articles 93 if len(articles) == 0 { 94 return title, "No stories to display", false 95 } 96 97 var str string 98 for idx, article := range articles { 99 row := fmt.Sprintf( 100 `[%s]%2d. %s [lightblue](%s)[white]`, 101 widget.RowColor(idx), 102 idx+1, 103 article.Title, 104 article.User.Username, 105 ) 106 107 str += utils.HighlightableHelper(widget.View, row, idx, len(article.Title)) 108 } 109 110 return title, str, false 111 } 112 113 func (widget *Widget) openStory() { 114 sel := widget.GetSelected() 115 if sel >= 0 && widget.articles != nil && sel < len(widget.articles) { 116 article := &widget.articles[sel] 117 utils.OpenFile(article.URL.String()) 118 } 119 }