github.com/wtfutil/wtf@v0.43.0/modules/subreddit/widget.go (about) 1 package subreddit 2 3 import ( 4 "fmt" 5 6 "github.com/rivo/tview" 7 "github.com/wtfutil/wtf/utils" 8 "github.com/wtfutil/wtf/view" 9 ) 10 11 type Widget struct { 12 view.ScrollableWidget 13 14 settings *Settings 15 err error 16 links []Link 17 } 18 19 func NewWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, settings *Settings) *Widget { 20 widget := &Widget{ 21 ScrollableWidget: view.NewScrollableWidget(tviewApp, redrawChan, pages, settings.Common), 22 23 settings: settings, 24 } 25 26 widget.SetRenderFunction(widget.Render) 27 widget.initializeKeyboardControls() 28 29 return widget 30 31 } 32 33 /* -------------------- Exported Functions -------------------- */ 34 35 func (widget *Widget) Refresh() { 36 links, err := GetLinks(widget.settings.subreddit, widget.settings.sortOrder, widget.settings.topTimePeriod) 37 if err != nil { 38 widget.err = err 39 widget.links = nil 40 widget.SetItemCount(0) 41 } else { 42 if len(links) <= widget.settings.numberOfPosts { 43 widget.links = links 44 widget.SetItemCount(len(widget.links)) 45 widget.err = nil 46 } else { 47 widget.links = links[:widget.settings.numberOfPosts] 48 widget.SetItemCount(len(widget.links)) 49 widget.err = nil 50 } 51 } 52 widget.Render() 53 } 54 55 func (widget *Widget) Render() { 56 widget.Redraw(widget.content) 57 } 58 59 /* -------------------- Unexported Functions -------------------- */ 60 61 func (widget *Widget) content() (string, string, bool) { 62 title := "/r/" + widget.settings.subreddit + " - " + widget.settings.sortOrder 63 if widget.err != nil { 64 return title, widget.err.Error(), true 65 } 66 67 var content string 68 for idx, link := range widget.links { 69 row := fmt.Sprintf( 70 `[%s]%2d. %s`, 71 widget.RowColor(idx), 72 idx+1, 73 tview.Escape(link.Title), 74 ) 75 content += utils.HighlightableHelper(widget.View, row, idx, len(link.Title)) 76 } 77 78 return title, content, false 79 } 80 81 func (widget *Widget) openLink() { 82 sel := widget.GetSelected() 83 if sel >= 0 && widget.links != nil && sel < len(widget.links) { 84 story := &widget.links[sel] 85 utils.OpenFile(story.ItemURL) 86 } 87 } 88 89 func (widget *Widget) openReddit() { 90 sel := widget.GetSelected() 91 if sel >= 0 && widget.links != nil && sel < len(widget.links) { 92 story := &widget.links[sel] 93 fullLink := "http://reddit.com" + story.Permalink 94 utils.OpenFile(fullLink) 95 } 96 }